Forum: Ruby on Rails Access to session data

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Rick W. (Guest)
on 2006-03-24 05:38
(Received via mailing list)

This, I hope, is a simply answered question.

Based on Agile Web D. with Rails (depot application), I'm
developing a single table application for contact info. There is only
an admin side to this, so there's always authentication.

Part of the info record (member) is changed_by and changed_at which I
automatically want updated. Changed_at looks after itself (yay!);
however changed_by doesn't. Since I know who is accessing the table
(everyone has a user_name) I've stored user_name in the session. I
can retrieve and display this information to the input form that is
collecting the info, so I know that there is session[:user_name].

Getting it into the active record is more difficult. What I have done
is inside the class for member.rb I've added a callback method:

   def before_save
       self.changed_by = "Rick"

and this will work. However,

   def before_save
       self.changed_by = session[:user_name]

does not, complaining that session is undefined :-(.

Obviously session is not available everywhere. How do I reference the
session correctly from inside the member class?

All flames and grace welcome.


Rick W.
Wilson B. (Guest)
on 2006-03-24 05:53
(Received via mailing list)
On 3/23/06, Rick W. <removed_email_address@domain.invalid> wrote:
> automatically want updated. Changed_at looks after itself (yay!);
>     end
> session correctly from inside the member class?

The first step to recovery is giving up on accessing the session from
the model.
That way madness lies:

However, you do have a number of good options. Here are a couple:

class Something < ActiveRecord::Base
  attr_writer :user
  def before_save
    return false unless @user && @user.can_update(self)
    self[:changed_by] = @user
That assumes that your User model has a method "can_update()" that
checks the user's permissions.

Then, in your controller, assuming @something is the instance of
Something that you're manipulating:
@something.user = session[:user]

Another alternative would look similar, but basically be a wrapper
around save that took a user as a parameter:

def save_by_user(user)
  raise SecurityError unless user.can_update(self) rescue nil
  self[:changed_by] = user
Jim M. (Guest)
on 2006-03-24 07:26
(Received via mailing list)
I solved the same problem with some very useful wiki entries and blogs I

and the accessing session[] from a model is discussed here...
This topic is locked and can not be replied to.