Securing my database with user session data

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

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

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