I'm using Rails 3.2. I have a search form that has radio buttons below it. It searches based on which of the radio buttons are selected. Currently I have this in my view:
= radio_button_tag(:ad_type, "free")
= label_tag(:ad_type_free, "free")
= radio_button_tag(:ad_type, "paid")
= label_tag(:ad_type_paid, "paid")
= radio_button_tag(:ad_type, "featured")
= label_tag(:ad_type_featured, "featured")
So my question is this, how do I set the default radio button to be selected? I have tried using radio_button_tag(:ad_type, "free", :checked => true)
, but after submitting the form, it always selects that radio button. What I want is to select the value based on the previous request. Should I get the value from the url params? If so, how do I set the initial default value(when there are no previous searches)? Thanks a lot.
Update
I've created a helper method ad_type_selected?
def ad_type_selected?(ad_type)
selected_ad_type = params[:ad_type] || "free"
(selected_ad_type == ad_type) ? true : false
end
And I have this in my view:
= radio_button_tag(:ad_type, "free", :checked => ad_type_selected?("free"))
However, the radio button still doesn't get selected. Checking the logs, I see that the first call to the helper returns true, and the others false, which is what I want. But problem is it still doesn't select the radio button. If I check the input tag, I can only see that the checked attribute is set to "checked".
Apparently, adding a checked attribute for all the radio buttons causes the last radio button to be always selected. So what I did is to just add a checked attribute if the params matched the radio button.
So for my example, I just used a helper to generate the appropriate radio button like so:
And have this in my view:
I know it's far from elegant, but it behaves correctly now.
I'm grave digging, but I just came across this.
So... this will set the first button by default (and always), but if the other params are selected they'll become true. Radio buttons will always have the last
true
button selected for you, so as long as you put your default option first in the list, set to true, and the rest set to:This snippet will set checked to false if params[:ad_type] is nil. Otherwise, it will set checked to true if params[:ad_type] is set to true.
Just in case you haven't seen the shorthand for if / then / else used above, it goes:
According to the docs,
checked
isn't an options hash parameter, it is just a boolean.This didn't worked (at least in rails 4):
It should be: