AnApprentice
AnApprentice

Reputation: 110960

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

I tried:

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

Thanks

Upvotes: 28

Views: 45078

Answers (2)

Abror Mukimov
Abror Mukimov

Reputation: 73

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")

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70819

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) %>

Upvotes: 47

Related Questions