15
<% 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.

logesh
  • 2,572
  • 4
  • 33
  • 60
  • Possible duplicate http://stackoverflow.com/questions/4708910/rails-how-to-make-a-conditional-radio-button-checked – Kees Sonnema Jul 02 '13 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. – logesh Jul 02 '13 at 12:35

2 Answers2

38

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>
Bachan Smruty
  • 5,686
  • 1
  • 18
  • 23
  • 1
    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](https://stackoverflow.com/questions/4228658/what-values-for-checked-and-selected-are-false) – dsomel21 Nov 01 '17 at 16:57
  • Actually, this will work, at least in Rails 5 it does. – Sasa Blagojevic Mar 24 '18 at 19:59
  • It works because if checked is false, Rails does not include the attribute. – Daniel Miller May 04 '22 at 22:20
2

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