Rails 从控制器的视图中设置实例变量
我正在尝试从视图中的控制器设置实例变量。例如:
class UsersController
def new
@admincheck = false
end
在视图:home.html.erb中,
<%= link_to "Sign up", signup_path, @admincheck => true, :class => "signup_button round" %>
在视图中将@admincheck设置为true,UsersController是否会通过接收@admincheck为true来响应?
我不确定您是否可以在视图中分配实例变量值以供控制器使用。谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法在控制器的视图中设置实例变量。
您可以将参数从视图传递到控制器,而不是这样做。
我认为您想添加一项检查,确保只有管理员才能“注册”。
为此,您可以检查控制器中的当前用户状态并继续。
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?
你应该简单地做这样的事情:
然后在你的控制器中你可以得到
admincheck
作为@admincheck = params[:admincheck]
You should simply do something like this:
Then in your controller you can get
admincheck
as@admincheck = params[:admincheck]
您无法从控制器的视图中设置实例变量。考虑一下请求响应周期:
浏览器->请求->控制器->查看->响应->浏览器
您想要将某些内容从视图传递到控制器,并且由于视图位于上图中的下线,因此它无法将变量传递给控制器,相反,您需要将数据作为表单字段传递并在控制器中捕获相同的数据,如下所示Pravin 和 Ashihsh 已经建议了。
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.