I would like to create a simple drop down list with static values which I could reuse anywhere in my Ruby on Rails application in a form. The drop down list is really simple, something like this:
<select>
<option value="5">5 minutes</option>
<option value="15">15 minutes</option>
<option value="30">30 minutes</option>
<option value="60">1 hour</option>
</select>
What is the most convenient way in Rails to create a “control” (I don’t know if this term is even used in Rails) like this and be able to use it anywhere in a form and bind it to a property of a model class?
UPDATE: Thanks for the answers, those seems to be really nice solutions.
However, would it be possible to extend the class that the form_for returns (not sure which one, is it FormHelper or FormBuilder?), in order to be able to do this in a view:
<%= form_for(@myObj) do |f| %>
<%= f.select_duration :duration %>
<% end %>
I started googling for how to extend the form helper, but could not figure it out yet.
UPDATE2: I can not answer my own question, so I put it here.
Finally figured out how to do it. Created a form_helper.rb file in app/helpers, and extended FormBuilder with the following code:
module FormHelper
def self.included(base)
ActionView::Helpers::FormBuilder.instance_eval do
include FormBuilderMethods
end
end
DURATIONS = [["5 Minutes", 5], ["15 minutes", 15], ["30 minutes", 30],["1 hour", 60]]
module FormBuilderMethods
def select_duration(method)
@template.select @object_name, method, @template.options_for_select(DURATIONS, @object.reminderTimeMinutes ? DURATIONS[@object.reminderTimeMinutes] : DURATIONS[0])
end
end
end
The last thing I am not sure about is whether it is a correct place for the DURATIONS constant (I am quite new to ruby, and ruby on rails).
Create a .rb file in app/initializers that creates your options as an array
Then, in the _forms in which you want to make use of these options,
Good luck.