Forum: Ruby on Rails RE: current user's id?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nathan L. (Guest)
on 2006-05-12 00:44
(Received via mailing list)
JP,

It depends on what authorization mechanism you are using, but if the
complete user info is stored in the session it would be something
like...

	session[:user].id

or, if you are just storing the id in the session and doing a lookup for
each access to user data...

	session[:user]

substitute your session variable for the "user" entry.

Hope that helps.

Nathan
Warren S. (Guest)
on 2006-05-12 02:11
(Received via mailing list)
If you mean the OS User-Id, there isn't one.  You could use cookies and
sessions and
assign an id.  Or do you mean a database id unique key?

Warren S.
Jeremy P. (Guest)
on 2006-05-12 02:30
Warren S. wrote:
> If you mean the OS User-Id, there isn't one.  You could use cookies and
> sessions and
> assign an id.  Or do you mean a database id unique key?
>
> Warren S.

I meant the id in the 'users' table.
This works for me:  @session['user'].id

Out of curiosity I looked at the complete 'user' hash:

@session['user']

And it returned the groups that the user is a member of. And I cannot
find where this information is placed in the session.

Is it normal for the user to include the group members from a
many-to-many relation (ie. users <-- groups_users --> groups)?

Thanks
JP
Jonathan V. (Guest)
on 2006-05-12 05:17
(Received via mailing list)
You should be careful about storing the user object in the session.
It's associations will be cached from the first time they are
accessed. Either just store the id and query the user each request, or
be very sure to reload the stored object and associations when
necessary.

I prefer the approach of storing the user id in the session and
querying it each request.

class User < ActiveRecord::Base
  cattr_accessor :current
end

Then populate User.current with each request:

class ApplicationController < ActionController::Base
  before_filter do
    User.current = User.find(session[:user_id])
  end
end

Then you can use User.current anywhere to get the currently logged in
user.

-Jonathan.
This topic is locked and can not be replied to.