Andreas S. wrote:
oh great, thanks lutz!
I am pretty new to RoR - and sometimes I think I still code ASP but
using RoR syntax - when I look at the oder code examples - I feel far
away from “aaaah, I get it!”. Most of the time I can’t find things in
the Api references - it is a bit complicated to find things here. I also
ask myself why to use classes? My code looks like asp classic I hope
this will change over the next weeks and month.
your idea about the session is good - I read about sessions and that
they can store complete objects.
Firstly, if a filter explicitly returns a “false” value than rails
thinks you want to abort the processing of the action and halts
execution. When there is no cookie the last statement executed in the
filter method is:
$login_ok = false
and assigments always return the new value. So the filter itself
Second, global variables will get you in trouble. If more than one
person at a time is using your app, the globals variable could have to
wrong values since they are global for all users in you app. This is
further complicated that most production rails sites runs multiple
server processes, each with it own global environment, and which process
serves the request is mostly random.
And for the most part, for ruby in general, embrace scope and simply
don’t use globals. Unless you have a very good reason.
Third, as mentioned, this is what sessions are for. You can store
entire record objects in the session but its not recomended since they
may become stale since they are not tied to the database without being
explicitly refreshed. It’s better to simply fetch a fresh objet on each
requet with a before_filter.
Here is how I would handle it:
session[:user_id] ||= cookies[:user_id]
session[:user_sid] ||= cookies[:user_sid]
@user = User.find_by_id(session[:user_id])
The cookies are fetched only if session[:user_id] is nil, meaning if you
assign a user_id another way, the potentially missing cookie values wont
Then we create an instance variable for the user. Using find_by_id
instead of just “find” prevents a record not found error, and simply
returns nil instead if the record doesn’t exist.
Then if someone is logged in, @user is a User object for that person.
And if no one is logged in, @user is nil. And @user is accessible in
all controllers and views. This lets you do simple things like:
redirect_to :action => ‘show’, :id => @user
redirect_to :action => ‘signup’
<% if @user %>
<%= link_to ‘Logout’, :action = ‘logout’ %>
<% else %>
<%= link_to ‘Login’, :action => ‘login’ %>
<% end %>