Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 3 how should I manage a model column with limited choices

In my Rails 3 application I have numerous models that have columns that have limited choices (IE a select box). It seems overkill in these cases to create another model and a relationship to the original model just to manage the choices.

One option I can think of is to just create a select box and have the choices in there, but that doesn't seem very DRY. Does anyone have a good suggestion how to handle this situation?

Thanks for looking.

like image 546
jklina Avatar asked May 17 '11 17:05

jklina


3 Answers

You could create a constant in your model like so

# formatted as an array of options, option being an array of key, value
OPTIONS = [['Email', 'email'], ['Text', 'text'], ['Email and Text', 'both']]

validates_inclusion_of :field, :in => OPTIONS

Which can then be used to populate a select menu in a view very easily

Example using formtastic

<%= f.input :field, :as => :select, :collection => Model::OPTIONS %>
like image 85
Jimmy Avatar answered Nov 15 '22 17:11

Jimmy


I usually do this with a constant list in the model.

class Model < ActiveRecord::Base
  PROPERTY_OPTIONS = ['Option One', 'Option Two', ...]
  validates_inclusion_of :property, :in => PROPERTY_OPTIONS
end

And in the view:

<%= f.select :property, Model::PROPERTY_OPTIONS %>
like image 24
Austin Taylor Avatar answered Nov 15 '22 18:11

Austin Taylor


You can also use the enum_column plugin: https://github.com/electronick/enum_column

You can then render your select boxes in your views as follows:

<%= f.select :status, Model.columns_hash['status'].limit %>

(Where Model is an example model name, such as Book or Product, or whatever it is your application is really about.)

like image 40
cailinanne Avatar answered Nov 15 '22 18:11

cailinanne