简体   繁体   English

如何从Rails的视图文件中读取参数?

[英]How to read parameters from view file in Rails?

I have a route: 我有一条路线:

http://127.0.0.1:3000/professor?roles=1

Now In my view file I have a checkbox, and I want to check if roles = 1 I want checkbox to be checked, if not, it must be unchecked. 现在,在我的视图文件中,我有一个复选框,我想检查是否Roles = 1我希望选中该复选框,如果没有选中,则必须取消选中该复选框。

I tried this: 我尝试了这个:

<input type="checkbox" <%=  (!@roles.blank? && !@roles.include?(0) ? " checked='checked' " : "") %> />

No errors, but it's not working. 没有错误,但是没有用。

Query parameters are available in the params hash: 查询参数在params哈希中可用:

# http://127.0.0.1:3000/professor?roles=1
params[:role] #=> "1"

Note that the values are strings. 请注意,这些值是字符串。

There's also a check_box_tag helper: 还有一个check_box_tag帮助器:

<%= check_box_tag nil, nil, params[:role] == "1" %>

You could also set an instance variable in your controller action: 您还可以在控制器操作中设置实例变量:

def index
  @role = params[:role].to_i
  # ...
end

and use that in your view instead: 并在您的视图中使用它:

<%= check_box_tag nil, nil, @role == 1 %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM