简体   繁体   中英

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. 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); @output_buffe...

There's also a little arrow pointing at $user

If I remove the $ from $user, I get this error:

undefined method `user' for 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.

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. To get over this limitiation, web developers use cookies or session variables to simulate maintenance of state, ie data, across requests.

Check out http://guides.rubyonrails.org/action_controller_overview.html#session

您也可以尝试

Thread.current[:email]

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