Rails: Where to store possible values of an attribute in ActiveResource
-
17-06-2021 - |
Domanda
Say I have an ActiveResource which has an schema with several attributes. One of the attributes is expected to have three values (defined by the API where the ActiveResource is talking to).
Since I am creating forms for this ActiveResource object, I want to know where should I store those three possible values? Imagine that in the form I want to show a drop down list.
Soluzione
- Store the possible values in a class as constants and an array.
- In your erb file, use collection.select to display a drop down using the array from the class created earlier. http://agilewarrior.wordpress.com/2011/10/22/rails-drop-downs/
- For validation, I guess you can override the validate method and reuse the array to make sure the value is one of the possible values. http://api.rubyonrails.org/classes/ActiveResource/Base.html
This answer in the Stackoverflow post has an ActiveRecord example for storing possible values in a separate class and then validating that an ActiveRecord attribute has one of those values: Enumeration in Ruby on rails
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow