Rails - How to make a conditional Radio Button checked?
Asked Answered
P

2

27

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 @permission.role_id == 2?

I tried:

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

Thanks

Pewter answered 16/1, 2011 at 23:47 Comment(0)
A
47

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) %>
Atomicity answered 16/1, 2011 at 23:49 Comment(5)
Neglects to account for the case of @permission.role_id == 2 as requested in the original question. Also, why not just use :checked => [email protected]_id.nil? sans ternary? Much more Ruby-esque.Tercet
Just tried it but no luck. Also had to update it to solve for the two use cases above... Ideas? <%= radio_button_tag 'permission[role_id]', '2', { :checked => ( (@permission.role_id.nil? || (@permission.role_id == 2) ? true : false) } %>Pewter
Strange, even doing { :checked => ( @permission.role_id == 2 ? false : false ) } is always checked truePewter
@Tercet Thanks for the feedback - I'm using the double-bang now.Atomicity
@Pewter - I've edited the answer - the problem was that checked isn't passed in the options hash, it's just a standard parameter.Atomicity
M
0

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")
Marylynnmarylynne answered 26/8, 2022 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.