[英]How to access global variable in a view in Ruby on Rails?
I have a User model. 我有一个用户模型。
I have a Session controller, in which I have a global user variable that is assigned as follows: 我有一个会话控制器,其中有一个全局用户变量,其分配如下:
$user = User.authenticate(params[:session][:email], params[:session][:password])
(I've made user global just to try to solve this problem, so if there's a better way please let me know!) (我已将用户设置为全局用户,以尝试解决此问题,因此,如果有更好的方法,请告诉我!)
I need to use the email of the logged in user as a parameter to send to Flex part of my website. 我需要使用登录用户的电子邮件作为参数发送到网站的Flex部分。 At the moment I'm creating the link as follows:
目前,我正在如下创建链接:
<%= link_to "secondpage", secondpage_path(:email => @session.$user.email)
But I'm getting the following error: 但我收到以下错误:
compile error /Users/benhartney/rails_projects/talk/app/views/layouts/_header.html.erb:12: syntax error, unexpected tGVAR ..._path(:email => @session.$user.email) ).to_s);
编译错误/Users/benhartney/rails_projects/talk/app/views/layouts/_header.html.erb:12:语法错误,意外的tGVAR ..._ path(:email => @ session。$ user.email)).to_s ); @output_buffe...
@output_buffe ...
There's also a little arrow pointing at $user 还有一个小箭头指向$ user
If I remove the $ from $user, I get this error: 如果我从$ user中删除$,则会出现此错误:
undefined method `user' for nil:NilClass
nil:NilClass的未定义方法“用户”
If I remove the 如果我删除
(:email => @session.user.email)
part, everything works fine, so I think all of the code except for this is ok. 部分,一切正常,所以我认为除此以外的所有代码都可以。
Can anyone tell me what I'm doing wrong? 谁能告诉我我做错了什么?
Thanks for reading! 谢谢阅读!
You can't have a global variable local to something, as far as I understand (this time, you can't have a global variable that is local to session) 据我了解,您不能在某事局部使用全局变量(这一次,您不能在会话局部使用全局变量)
Try using :email => $user.email
if you're adamant that you need a global variable for something. 如果您坚决需要某种全局变量,请尝试使用
:email => $user.email
。
I think what you are looking for is a session variable. 我认为您正在寻找的是会话变量。
Rails is primarily a framework for creating web applications, and http is stateless, ie each request knows nothing about what went on before. Rails主要是用于创建Web应用程序的框架,而http是无状态的,即每个请求都不知道之前发生了什么。 To get over this limitiation, web developers use cookies or session variables to simulate maintenance of state, ie data, across requests.
为了克服这种限制,Web开发人员使用cookie或会话变量来模拟跨请求的状态(即数据)的维护。
Check out http://guides.rubyonrails.org/action_controller_overview.html#session 查看http://guides.rubyonrails.org/action_controller_overview.html#session
您也可以尝试
Thread.current[:email]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.