12
votes

I am using the simple_form gem https://github.com/plataformatec/simple_form to create some input fields; one of which is a radio button group, like this:

<%= f.input :due_date, :collection => ['Today', 'Tomorrow', 'In 3 Days'], :as => :radio %>

So this field in the database "due_date" is a Date. But rather than letting people click on that smallish calendar, we know that generally people just want these three options. And I do want to use radio button. But the output of this line suggest that if I hit the submit button now, the due_date param will have the values stated there, i.e., Today, Tomorrow or In 3 Days. Here's the output HTML for the Today part.

<span>
<input class="radio optional" id="project_due_date_today" name="project[due_date]" type="radio" value="Today">
<label class="collection_radio" for="project_due_date_today">Today</label>
</span>

What I want ideally is like :

<%= f.input :due_date, :collection_to_params => [Date.today, Date.tomorrow, Date.today+3], :display_value => ['Today', 'Tomorrow', 'In 3 Days'], :as => :radio %>

So when a user clicks on one, and submits, I actually get some ISO date sent to the server.

Any ideas?

Thanks!

2
I haven't used simple_form, but usually with Rails it's worth trying a hash: :collection => {'Today' => Date.today, 'Tomorrow' => Date.tomorrow, 'In 3 Days' => Date.today+3}Alex
Hey Alex, thanks for the input, I will keep that in mind, but I'd found the simple for answer.Nik So
Small notice, that there are radio is deprecated, and replaced to a radio_buttons.Dmitry Polushkin

2 Answers

31
votes
<%= f.input :due_date, 
:collection => [[Date.today, 'Today'], [Date.tomorrow, 'Tomorrow'], [Date.today+3, 'In 3 Days']], 
:label_method => :last, 
:value_method => :first, 
:as => :radio_buttons %>

So you can pass either an array of arrays to the collection hash, and then the there are two more options that can be passed to specify the VALUE of this input and the visible label of this input and they are properly named label_method and value_method. the word method being, what method to call on the individual item of the collection in question to retrieve the label or the value. In the array of array's case, array.first is my value, array.last if my label. Hence the code above

2
votes

This is what I've got from Nik So's answer with all comments applied:

<%= f.input :due_date, 
collection: [['Today', Date.today], ['Tomorrow', Date.tomorrow], ['In 3 Days', Date.today+3]],
as: :radio_buttons %>