# Session variable model validation

**URL:** <https://www.ruby-forum.com/t/session-variable-model-validation/142370>\
**Category:** Rails\
**Created:** [July 7, 2008, 12:27pm UTC](https://www.ruby-forum.com/t/session-variable-model-validation/142370 "2008-07-07T12:27:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![iceburging](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/a9a28c/32.png) [@iceburging](https://www.ruby-forum.com/u/iceburging)\
**Post date:** [July 7, 2008, 12:27pm UTC](https://www.ruby-forum.com/t/session-variable-model-validation/142370/1 "2008-07-07T12:27:02Z")

</div>

I am trying to implement a basic user permissions system with three  
access levels; 1, 2, and 3 (with 1 being the highest). A user should be  
able to create a new user but they should only at or below their own  
permissions level. e.g. a level 2 user who is logged in should only be  
able to create a level 2 or level 3 user.

I have sessions set up such that a user must be logged in to access the  
site and their user\_id is stored in a session variable. The new and edit  
views for the User model are designed so that only the appropriate  
levels are displayed to the user. This is achieved by retrieving the  
user\_id from the session data, getting current users level, and using  
the information to populate a drop down list.

I would like to add validation to my Users model to check that the user  
who is adding user has the appropriate access level. This should protect  
the database against someone bypassing the form.

I have tried to add the custom validation seen below but the session  
variable :user\_id is not available to the model.

def appropriate\_level  
user = User.find(session[:user\_id])  
errors.add\_to\_base(“Cannot set user level above #{user.level}” ) if  
level \> user.level  
end

Any ideas?

---

<div class="post-metadata">

**Author:** ![iceburging](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/a9a28c/32.png) [@iceburging](https://www.ruby-forum.com/u/iceburging)\
**Post date:** [July 7, 2008, 1:03pm UTC](https://www.ruby-forum.com/t/session-variable-model-validation/142370/2 "2008-07-07T13:03:35Z")

</div>

On 7 Jul 2008, at 11:27, Russ Giles wrote:

> def appropriate\_level  
> user = User.find(session[:user\_id])  
> errors.add\_to\_base(“Cannot set user level above #{user.level}” ) if  
> level \> user.level  
> end

Pass down the current user in some way (eg have an instance variable  
called created\_by. Doesn’t have to be reflected in the database if you  
don’t want it to.)

Fred
