# Securing my database with user session data

**URL:** <https://www.ruby-forum.com/t/securing-my-database-with-user-session-data/97130>\
**Category:** Rails\
**Created:** [July 5, 2006, 6:17am UTC](https://www.ruby-forum.com/t/securing-my-database-with-user-session-data/97130 "2006-07-05T06:17:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![brianzimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6f9a4e/32.png) [@brianzimmer](https://www.ruby-forum.com/u/brianzimmer)\
**Post date:** [July 5, 2006, 6:17am UTC](https://www.ruby-forum.com/t/securing-my-database-with-user-session-data/97130/1 "2006-07-05T06:17:41Z")

</div>

I have a few forms that adds information to a database, and one of the  
fields is “user\_id” This field relates the stored information (in this  
case a “route”) with the user who entered it.

I have a few questions.

First, is the controller the best place to set the user\_id? Right now I  
am using,  
@route = Route.new  
@route.user\_id = session[:user].id  
@route.save

Should this go in the model instead?

I tried this but I get an error for using session[:user].id: “undefined  
local variable or method `session’ for #”

Also, is there a check I can put in the model to make sure that no entry  
is edited with a user id different than the current user.

Something like  
def validate  
errors.add(:user\_id, “This is not your route!”) unless :user\_id ==  
session[:user].id  
end

But I still get the error “undefined local variable or method `session’  
for #”

Thanks in advance,  
Brian

---

<div class="post-metadata">

**Author:** ![brianzimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/6f9a4e/32.png) [@brianzimmer](https://www.ruby-forum.com/u/brianzimmer)\
**Post date:** [July 5, 2006, 4:00pm UTC](https://www.ruby-forum.com/t/securing-my-database-with-user-session-data/97130/2 "2006-07-05T16:00:45Z")

</div>

You can’t easily access the current user from a model – it breaks MVC  
as the Model should not have any knowledge of the current user. It can  
be done, I believe – search these forums for something like ‘session  
user model’ and you should find quite a few posts relating to it (I  
remember reading stuff a while ago).

So the answer is it should go into the controller. The simplest away to  
ensure that the user can only edit their own items is to do:  
current\_user.items.find(params[:id]) for example, which will through an  
error if it doesn’t belong to current\_user (assuming your auth model  
sets a current\_user, otherwise  
User.find(session[:user].id).items.find(params[:id]).

HTH
