How to make radio button checked by default based on different user role?
Asked Answered
A

2

17
<% if role.name == "Administrator" %>
     <%= f.radio_button:status,'available', :checked => (params[:status] == nil ? true : params[:status]) %><label>Available</label>
     <%= f.radio_button:_status,'not available' %><label>Not Available</label>
<% else %>
     <%= f.radio_button:_status,'available' %><label>Available</label>
     <%= f.radio_button:_status,'not available' %><label>Not Available</label>
<% end %>

By default i want the available radio button to be checked in case of administrator and not available radio button for rest of user. But he can change it and when viewing for editing it should show the one he/she has selected and not the default one.

How can i do this? please help me.

Actiniform answered 2/7, 2013 at 11:15 Comment(2)
Possible duplicate #4709410Amphoteric
@KeesSonnema: I dont think there is any thing that is similar to what they have asked for. Please read my question again and check for difference.Actiniform
A
39

Try the following code.

<%= f.radio_button:_status,'available', :checked => (role.name == "Administrator") %><label>Available</label>
<%= f.radio_button:_status,'not available', :checked => (role.name != "Administrator") %><label>Not Available</label>
Agnail answered 2/7, 2013 at 11:44 Comment(3)
This will not work, because checked will always be true if it is inserted in an HTML element, no matter what it is set as. You can read more on it hereKapor
Actually, this will work, at least in Rails 5 it does.Melamine
It works because if checked is false, Rails does not include the attribute.Reparable
L
3

If you take a look at the documentation for rails radio_button_tag you would see it accepts the following params:

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

So it would be enough the following code

<%= f.radio_button:_status,'available', role.name == "Administrator" %><label>Available</label>
<%= f.radio_button:_status,'not available', role.name != "Administrator" %><label>Not Available</label>

Without the need of adding a "checked" property that might result in an unwanted behaviour

Locality answered 11/9, 2018 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.