Reputation: 843
The goal is to pass a specific boolean value (true or false) with a specific link.
I've tried with:
<%= link_to "new test", new_test_path(:crazy => true) %>
URL: /tests/new?crazy=true
view
<div class="field">
<%= f.radio_button :crazy, true %> True
<%= f.radio_button :crazy, false %> False
</div>
static_pages_controller
def home
@test = Test.new
...
end
but none of the radio buttons is selected when I click on that link.
Upvotes: 2
Views: 1526
Reputation: 9747
We can't get values from query string as Boolean. You will need to check all the possibilities or just do something like:
params[:crazy] == 'true'
However, string comparison is always costly as per string length. So, you should try to minimize it. You may check centralized method solution given by Ismriv.
I guess this will be best for you:
Your link:
<%= link_to "new test", new_test_path(:crazy => '1') %>
Your new
action:
def new
@test = Test.new(:crazy => (params[:crazy] == '1'))
...
end
Your radios:
<div class="field">
<%= f.radio_button :crazy, true %> True
<%= f.radio_button :crazy, false %> False
</div>
Upvotes: 3
Reputation: 66
The radio_button method (http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-radio_button) does not check the radio button automatically based on request parameters.
<%= f.radio_button '', :crazy, 'true', { checked: params[:crazy] == 'true' } %> True
<%= f.radio_button '', :crazy, 'false', { checked: params[:crazy] == 'false' } %> False
Do note the object_name / method distinction in rails, which generates parameters named "object_name[method]" by convention. If you really want your parameter to only be named "crazy", leave object_name empty.
Upvotes: 0