简体   繁体   中英

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.

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:

# 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 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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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