Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a default value for a collection of radio buttons in Formtastic?

I'm building a form in Rails3 and Formtastic. I have the following field:

<%= f.input :housing, :as => :radio, :collection => {"Awesome" => "one", "Great" => "two", "Nice" => "three"} %>

Which generates HTML similar to:

<input id="post_one" name="post" type="radio" value="one" />Awesome</label>
<input id="post_two" name="post" type="radio" value="two" />Great</label>
<input id="post_three" name="post" type="radio" value="three" /> Nice</label>

That work flawlessly!

Now I'd like to know how I could pass in an option that would mark "Great" as the default (selected) value. I tried doing the following, but I can't get it to work.

<%= f.input :housing, :as => :radio, :collection => {"Awesome" => "one", "Great" => "two", "Nice" => "three"}, :default => "one" %>

I also tried passing in :selected and :checked instead of :default but alas, it does not work.

Does anybody know of a way to do this?

Thanks!


Edit: Aditya brings up a very good point. Some searching yielded this helpful tip.

like image 995
Yuval Karmi Avatar asked Dec 27 '10 07:12

Yuval Karmi


1 Answers

Set the HTML options on a specific radio input option with a 3rd element in the array for a collection member as follows:

<%= f.input :author, :as => :radio, :collection => [["Test", 'test'], ["Try", "try", {:checked => true}]]
like image 137
Ivan Avatar answered Nov 15 '22 06:11

Ivan