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!
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) %>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With