Rails 3, checked radio button with if function

馋奶兔 提交于 2019-12-25 07:35:11

问题


I have a radio button within my form as follows

    <div class="btn-group" data-toggle="buttons-radio">
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2007' %> 2007
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2008' %> 2008
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2009' %> 2009
    </div>

I am using twitter bootstrap

I want to do something like the following:

    <div class="btn-group" data-toggle="buttons-radio">
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2007', if @dates.start_year == 2007 :checked => true end %> 2007
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2008', if @dates.start_year == 2008 :checked => true end %> 2008
      <%= f.radio_button :start_year, :class=> "btn", :value=> '2009', if @dates.start_year == 2009 :checked => true end %> 2009
    </div>

But I get the following error:

syntax error, unexpected keyword_ensure, expecting ')'
syntax error, unexpected keyword_end, expecting ')'

I must be making a mistake in the if statement within the radio button, but I'm not sure how exactly to correct this


回答1:


Try

<%= f.radio_button :start_year, :class=> "btn", :value=> '2007', :checked => Proc.new { @dates.start_year == 2007 ? true : false } %> 2007



回答2:


I know this is an old question, but maybe it helps others. I don't think we need Proc here, we can just pass boolean value to :checked key. Also, @dates.start_year == 2007 ? true : false can be simplified to @dates.start_year == 2007.

So, the result will be as simple as

<%= f.radio_button :start_year, :value=> '2007', :checked => @dates.start_year == 2007%> 2007


来源:https://stackoverflow.com/questions/13208604/rails-3-checked-radio-button-with-if-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!