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.

2
  • Possible duplicate stackoverflow.com/questions/4708910/… Commented Jul 2, 2013 at 11:23
  • @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. Commented Jul 2, 2013 at 12:35

2 Answers 2

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

3 Comments

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 here
Actually, this will work, at least in Rails 5 it does.
It works because if checked is false, Rails does not include the attribute.
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

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.