Ruby-on-rails 如何根据不同的用户角色默认选中单选按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17424130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:16:44  来源:igfitidea点击:

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

ruby-on-railsruby-on-rails-3radio-button

提问by logesh

<% 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 availableradio button to be checked in case of administrator and not availableradio 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.

默认情况下,我希望在available管理员和not available其他用户的单选按钮的情况下选中单选按钮。但是他可以更改它,并且在查看以进行编辑时,它应该显示他/她选择的那个而不是默认的。

How can i do this? please help me.

我怎样才能做到这一点?请帮我。

回答by Bachan Smruty

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>

回答by Rodrigo Garcia

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

如果您查看 rails radio_button_tag的文档,您会看到它接受以下参数:

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

无需添加可能导致不良行为的“已检查”属性