简体   繁体   中英

Rails setting Instance Variable from View for the Controller

I am trying to set the instance variable from the controller from the view. For example:

class UsersController

def new
  @admincheck = false
end

in view: home.html.erb

<%= link_to "Sign up", signup_path, @admincheck => true, :class => "signup_button round" %>

with setting @admincheck to true in the view, will the UsersController respond to that by receiving @admincheck that is true?

I am unsure whether you can assign instance variables values in the view for the controller to use. Thanks

You cant set the instance variable in view for controller. Instead of doing this you can pass a parameter from view to controller. I think you want to add a check that only admin should be able to 'Sign Up'. For this you can check the current user status in the controller and proceed.

Try to use Filters to handle those kind of things. It shouldn't be the responsibility of the view to handle the authentication decision for the next request.

What do you want to do exactly?

You should simply do something like this:

<%= link_to "Sign up", signup_path(:admincheck => true), :class => "signup_button round" %>

Then in your controller you can get admincheck as @admincheck = params[:admincheck]

You can't set a instance variable from the view for the controller. Think of with respect to request response cycle:

Browser -> Request -> Controller -> View -> Response -> Browser

You want to pass something from view to controller and as view is down the line in the above illustration it can't pass a variable to controller, instead you will need to pass the data as form field and capture the same in the controller as already suggested by Pravin and Ashihsh.

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