# Getting session data to the model

**URL:** <https://www.ruby-forum.com/t/getting-session-data-to-the-model/48577>\
**Category:** Rails\
**Created:** [November 22, 2005, 11:44am UTC](https://www.ruby-forum.com/t/getting-session-data-to-the-model/48577 "2005-11-22T11:44:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![robbie.carlton](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9de053/32.png) [@robbie.carlton](https://www.ruby-forum.com/u/robbie.carlton)\
**Post date:** [November 22, 2005, 11:44am UTC](https://www.ruby-forum.com/t/getting-session-data-to-the-model/48577/1 "2005-11-22T11:44:04Z")

</div>

Hi everyone.

I’m writing the admin area of a website, which has several users. The id  
of  
the current user is stored in the session. There are several models that  
the  
user can edited (article, link, customer etc), and whenever a user edits  
a  
model I would like to record this fact in a textfield of the model, so  
that  
lists of the various models can display who last edited them. I wrote a  
module to include into each model that wants this behaviour, but then I  
realised I can’t get at the user\_id from the model, and that I would  
have to  
go edit all my controllers, passing in the user\_id to each different  
model  
wherever an instance is created. This is obviously hairy duplication,  
and  
I’m sure there is a clever way to factor it out, I just can’t see where.

Cheers.

Robie

---

<div class="post-metadata">

**Author:** ![robbie.carlton](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9de053/32.png) [@robbie.carlton](https://www.ruby-forum.com/u/robbie.carlton)\
**Post date:** [November 22, 2005, 1:04pm UTC](https://www.ruby-forum.com/t/getting-session-data-to-the-model/48577/2 "2005-11-22T13:04:37Z")

</div>

Have a look at the way Bruce P. has done it in ModelSecurity  
([http://perens.com/FreeSoftware/ModelSecurity/Tutorial.html](http://perens.com/FreeSoftware/ModelSecurity/Tutorial.html)).

Basically he creates a class attribute on User called ‘current’, and  
uses a before\_filter to pull the current user out of the session and  
set it in the User class.

It’s quite a neat solution, and one that I’m adopting in my own code.  
Several of my tables have a ‘created\_by\_id’ that automatically gets  
set to the id of the current user on creation, and that can be done  
entirely in the model.

Pete Y.

---

<div class="post-metadata">

**Author:** ![robbie.carlton](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9de053/32.png) [@robbie.carlton](https://www.ruby-forum.com/u/robbie.carlton)\
**Post date:** [November 22, 2005, 1:04pm UTC](https://www.ruby-forum.com/t/getting-session-data-to-the-model/48577/3 "2005-11-22T13:04:38Z")

</div>

Thanks. Thats perfect.
