Rails Models: how would you create a pre-defined set of attributes?

I assume that you are going to have more than a few of these multiple-choice attributes, and would like to keep things tidy.

I would recommend the store it in the database approach only if you want to modify the choices at runtime, otherwise it would quickly become a performance hit; If a model has three such attributes, it would take four database calls instead of one to retreive it.

Hardcoding the choices into validations is a fast way, but it becomes tedious to maintain. You have to make sure that every similar validator and drop-down list etc. use matching values. And it becomes quite hard and cumbersome if the list becomes long. It’s only practical if you have 2-5 choices that really won’t change much, like male, female, unspecified

What I’d recommend is that you use a configuration YAML file. This way you can have a single tidy document for all your choices

# config/choices.yml

morality:
  - Good
  - Evil
genre:
  - Action
  - Suspense
  - Western
hair_color:
  - Blond
  - Brown
  - Black

Then you can load this file into a constant as a Hash

# config/initializers/load_choices.rb

Choices = YAML.load_file("#{Rails.root}/config/choices.yml")

Use it in your models;

# app/models/character.rb

class Character < ActiveRecord::Base
  validates_inclusion_of :morality, in: Choices['morality']
  validates_inclusion_of :genre, in: Choices['genre']
  # etc…
end

Use them in views;

<%= select @character, :genre, Choices['genre'] %>

etc…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)