2

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.

complete_morons
  • 823
  • 2
  • 8
  • 14
  • You need to set the value of the attribute to be true in the controller. If it's `true`, the first button will check. If it's `false`, the second button will check. It's probably `nil`. – Mark Swardstrom Sep 13 '14 at 14:58
  • Could you please write an answer to see how to actually do it? I've tried setting value in test_params with [:crazy => 'true'], but it still doesn't work. – complete_morons Sep 13 '14 at 15:12

2 Answers2

3

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>
Community
  • 1
  • 1
RAJ
  • 9,697
  • 1
  • 33
  • 63
0

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.

Jonas Witt
  • 66
  • 2