How to access global variable in a view in Ruby on Rails? - 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!

I think what you are looking for is a session variable.
Rails is primarily a framework for creating web applications, and http is stateless, i.e. 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, i.e. data, across requests.
Check out http://guides.rubyonrails.org/action_controller_overview.html#session

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.

You can also try
Thread.current[:email]

Related

Session exists even after destroying

I have a session variable with name session[:computerid] and while login it's set to "comp--001". While sign out i am deleting session like as follows
session.delete(:computerid)
But after doing that also if i debug session[:computerid] it's showing value "comp--001".
My session_store.rb file has the following code:
Rails.application.config.session_store :cookie_store, key: '_sample_app_session', :domain=>:all
Could you suggest me a solution to solve this?
Could you try setting it to nil? Like:
session[:computerid] = nil
This is the most common pattern in rails.
Hope it helps!
Good luck!
Ruby on Rails doesn't know what you want to keep or not when a user signs-out.
Say for example you have a session[:language] that is useful for every user, even anonymous ones. You wouldn't want to erase it to display the default language after the user has gone through the trouble of selecting one in particular.
So, delete the session objects you need to, like session[:user]=nil and keep the rest. If you have a lot of them to delete, make yourself a logout helper.
If you know you can swipe the whole session, use the reset_session

Rails refuses to forget code, leaving ssl and initialize method errors

I am noticing a pattern of rails acting as if a line of code is still written once it has been deleted, and I think it may have something to do with changing its defaults too much. I have two examples.
In the first, I set config.force_ssl => true in my config file (a major mistake) and immediately got an error on a page where I was introducing an api via a script tag:
My server gave me an error because the response length of the input wasn't known. I tried enabling streaming in my controller, and it failed. I even tried setting config.force_ssl => false, but this too was useless. So, I deleted the config.force_ssl => true line, but in Firefox, the page with the error continued to route to an "https://" url and then give me the same error. Chromium did not, so I switched to using that, but to this day, I still cannot load the page in Firefox without an error.
Now for the second issue. More recently, I created a model where I wanted to create a custom initialize method with four parameters.
association.rb
def initialize(tag_index, relative_index, type, relevance)
#assigning variables
end
In my controller, I assigned these accordingly.
tags_controller.rb
a = Association.new(id, tag_two.id, type, relevance)
Immediately, I get an error that I have 4 for 2 parameters. Thinking it's just rails being picky, I take away "type" and "relevance." Now, though, I get an error message telling me there is no method 'check_validity!' for class 30:Fixnum. So, I remove the initialize function altogether, and just as before, Rails refuses to recognize that the lines of code have been deleted, giving me errors when I enter parameters for Association.new, and telling me I'm missing parameters when I don't enter any at all.
If anyone can help with the little pieces such as how to fix a response length error with ssl, or how to deal with the 'check_validity!' method, that would be great. Better, though, would be if someone could explain why Rails refuses to let old pieces of code be deleted. This is something that has frustrated me to no end, and I can't find anything on any of these forums about how to fix it.
Thanks so much!

Confirm on Apache Passenger deployment: rails access session in model

I am using this to access session in Model.
http://www.zorched.net/2007/05/29/making-session-data-available-to-models-in-ruby-on-rails/
Can anybody confirm that it will work with Apache + Passenger deployment too?
Or if there are any other alternatives to achieve the same?
Thanks,
Imran
I did not find any code on the internet that works, so I did some research and wrote my own. It works for Rails 3.2.x and probably on some other versions.
Insert this in your ApplicationController
# Set a filter that is invoked on every request
before_filter :_set_current_session
protected
def _set_current_session
# Define an accessor. The session is always in the current controller
# instance in #_request.session. So we need a way to access this in
# our model
accessor = instance_variable_get(:#_request)
# This defines a method session in ActiveRecord::Base. If your model
# inherits from another Base Class (when using MongoMapper or similar),
# insert the class here.
ActiveRecord::Base.send(:define_method, "session", proc {accessor.session})
end
I will not remind you that accessing your session from a model may lead to bad code. Other posts may tell you, that you are stupid. Though there are some valid reasons to access the session from your model, like implementing a Model.save method, that saves to the current users session.
Yes. It is the only efficient way I found to use session data in model. I also used it and never faced any deployment issue with Apache + passenger.
But you need to confirm when you will be playing with session values. On each new request to server, session value gets stored in thread and we can access it in model. If you are applying any logic by using thread value, then also make sure with situation when thread value might be nil also.
Because I got an issue where on development, my every code worked fine but on production, during starting server it caused an issue as initially it considered thread value as nil.

session[:key] = value doesn't work

I am trying to make use of session data in my application and for some reason I don't have something setup right.
The code:
session[:key] = some_value
Generates the following error:
The error occurred while evaluating nil.[]
Other controllers don't have an issue with the session, so I am guessing I missed some basic configuration thing somewhere.
Ok, I think I got it figured out now. I had a slightly more complex situation that my example. I actually had the following:
session[:chat_history][chat.from.id] ||= []
So I had an error with double array. I added the following:
session[:chat_history] ||= []
Problem was the first time I did this, I put it in a before_filter method. Apparently the session object is nil in the before_filter method, at least the way I have my application setup.
So I moved the initializer to the methods that actually access the session and life is good again.
It looks like the session variable is nil which makes me think the framework couldn't set it for one of these reasons:
Browser passed in no cookie for the session
Browser passed in a cookie but it didn't match anything the server expected
It was stated that some controllers work. Did something have the opportunity to create a session for the user before those controllers ran?

Can ActiveResource POST a create instead of PUTTing it when an id is specified?

I'm calling a rails app from another using ActiveResource. I need to supply the id of the new object to the first app (yes, controller create in this app knows how to handle receiving an id), so I do something like this:
a = ActiveResourceModel.new(:id => 1231231, :name => "test")
a.save
However, instead of doing POST to create a new resource it PUTs it, causing the receiving app to try to update the resource with id 1231231, which of course doesn't exist (I want to create it!), so I end up receiving a 404 error because of this.
Doing some testing the problem seems to be in ActiveResourceModel.new? which returns false, while ActiveResourceModel.exists? returns false too (Great, two methods which are supposed to be opposite return the same!).
Checking the AResource source and documentation, the new? method checks for the presence of the id and the exists? checks for the remote resource, making both returning the same.
Why exactly you need to pass the id to create a new object? Doesn't make sense.
Anyway, You can try to call create method instead of save.
I have the opposite problem. I EXPECT a PUT when calling AR.create with an id (since it implies the record already exists). However, with Rails 3.1 and up, it seems like the same code in Rails 3.0 that called PUT now in fact calls POST. Can anyone confirm this change? (Since I have control of the receiving server, I simply adjusted the POST code to have the same behavior as my old PUT code).

Resources