Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails equivalent to Django's "choices"

I know there is no real equivalent in Rails but my question is mostly about best practice...

In Django, if you want to limit a model field to a limited set of choices, you would do something like this (in your model):

COLOR_CHOICES = (('B', 'Blue'), ('R', 'Red'))
item_color = models.CharField(choices=COLOR_CHOICES)

From my (basic) understanding of Rails, I can achieve something similar, for example, by using a select tag in the forms dealing with adding/editing that model...

My question however is, where would it be appropriate to declare the "choices" hash (again I'm guessing here that a hash is what I need?). Basically I just want it to be easily re-usable in any forms where I might need to present those choices, and when it comes to validating at the model level.

Any help/tips would be appreciated!

like image 520
jeannicolas Avatar asked Dec 13 '10 23:12

jeannicolas


2 Answers

On the validation side of things, probably validates_inclusion_of is what you need:

class Coffee < ActiveRecord::Base
  validates_inclusion_of :size, :in => %w(small medium large),
    :message => "%{value} is not a valid size"
end

As for generating the helper, you can try something like:

class Coffee < ActiveRecord::Base
  @@coffe_size = %w(small medium large)

  validates_inclusion_of :size, :in => @@coffe_size,
    :message => "%{value} is not a valid size"

   def self.coffee_size_options
       @@coffe_size.map{ |z| [z,z]} 
   end
end

And then in some helper:

<%= select(:coffee, :size, Coffee.coffee_size_options) %>
like image 121
krusty.ar Avatar answered Oct 21 '22 19:10

krusty.ar


You can simply use enum

class Coffee < ActiveRecord::Base
  enum color: [ :blue, :red, :green ]
end

More information here : https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html

like image 35
Supernini Avatar answered Oct 21 '22 18:10

Supernini