28

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

2 Answers 2

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) %>
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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) } %>
Strange, even doing { :checked => ( @permission.role_id == 2 ? false : false ) } is always checked true
@coreyward Thanks for the feedback - I'm using the double-bang now.
@AnApprentice - I've edited the answer - the problem was that checked isn't passed in the options hash, it's just a standard parameter.
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.