简体   繁体   English

从控制器的Rails设置实例变量

[英]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 查看: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? 在视图中将@admincheck设置为true,UsersController会通过接收为true的@admincheck来对此做出响应吗?

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] 然后,在您的控制器中,您可以将admincheck作为@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. 您想将某些东西从视图传递到控制器,并且由于视图位于上图中的线下,因此它无法将变量传递给控制器​​,相反,您将需要将数据作为表单字段传递并在控制器中捕获相同的数据由Pravin和Ashihsh提出。

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

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