Access to session data


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.

On 3/23/06, Rick W. [email protected] wrote:

automatically want updated. Changed_at looks after itself (yay!);
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

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs