开发者

Rails - How to make a conditional Radio Button checked?

Given a radio button like so:

<%= radio_button_tag 'permission[role_id]', '2' %>

How can I make the radio buttons checked status condition. To only be checked if @permission.role_id.nil? or if @permis开发者_如何学Csion.role_id == 2?

I tried:

<%= radio_button_tag 'permission[role_id]', '2', @permission.role_id.nil? ? {:checked => true} : {:checked => false} %>

Thanks


The documentation for radio_button_tag says that checked isn't an options hash parameter, it's just a normal one:

radio_button_tag(name, value, checked = false, options = {})

So, you need to do this:

<%= radio_button_tag 'permission[role_id]', '2', !!(@permission.role_id.nil? || @permission.role_id == 2) %>


If you are using rails 7, the answer given by @skilldrick doesn't work. You have to use a hash instead of a just parameter.

...
form.radio_button :example_field, :example_value, checked:(example_value == "Example Value")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜