2014-09-13 45 views
0

目标是通过特定的链接传递特定的布尔值(true或false)。Rails 4:在新动作上传递布尔值

我已经试过:

<%= link_to "new test", new_test_path(:crazy => true) %> 

网址:/测试/新疯狂=真

视图

<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 

但是当我单击该链接时没有选中单选按钮。

+0

您需要在控制器中将该属性的值设置为true。如果它是'true',则第一个按钮将被检查。如果它是'假',第二个按钮将被检查。这可能是'无'。 – Swards 2014-09-13 14:58:56

+0

你可以写一个答案,看看如何实际做到这一点?我试着用[:crazy =>'true']在test_params中设置值,但它仍然不起作用。 – 2014-09-13 15:12:39

回答

1

我们无法从查询字符串中将值作为布尔值。您需要做好一切准备或者只是像做:

params[:crazy] == 'true' 

但是,字符串比较总是昂贵的每串的长度。所以,你应该尽量减少它。您可以检查由Ismriv给出的集中式方法解决方案。


我想这将是最适合你:

您的链接:

<%= link_to "new test", new_test_path(:crazy => '1') %> 

new行动:

def new 
    @test = Test.new(:crazy => (params[:crazy] == '1')) 
    ... 
end 

您的收音机:

<div class="field"> 
    <%= f.radio_button :crazy, true %> True 
    <%= f.radio_button :crazy, false %> False 
</div> 
0

radio_button方法(http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-radio_button)不会根据请求参数自动检查单选按钮。

<%= f.radio_button '', :crazy, 'true', { checked: params[:crazy] == 'true' } %> True 
<%= f.radio_button '', :crazy, 'false', { checked: params[:crazy] == 'false' } %> False 

请注意rails中的object_name/method的区别,它根据约定生成名为“object_name [method]”的参数。如果你真的希望你的参数只被命名为“疯狂”,请将object_name留空。