Validate Object Ownership (user_id) in model, or in controller?

Quick best practices question …

I have a number of models with a user_id attribute

I am using the acts_as_authenticated plugin which lets you use
something like current_user to extract the current user from the
session. I have used this in my controllers successfully.

Would it be “wrong” to use this as a model validation? How would I
make this accessible to the model? I can’t seem to get it to work from
within a model.

I’d like to write something that checks every model update, and
verifies ownership (previous owner is current owner)

Thanks in advance for your help

Astorian wrote:

Quick best practices question …

I have a number of models with a user_id attribute

I am using the acts_as_authenticated plugin which lets you use
something like current_user to extract the current user from the
session. I have used this in my controllers successfully.

Would it be “wrong” to use this as a model validation? How would I
make this accessible to the model? I can’t seem to get it to work from
within a model.

I’d like to write something that checks every model update, and
verifies ownership (previous owner is current owner)

Thanks in advance for your help

You are saying there is a user_idcolumn?

A model validation like this makes sense to me:

validates_each :user_id do |record, attr_name, value|
record.errors.add(attr_name, ‘cannot be changed by current user’)
unless User.current.id = value
end

User.current is supposed to give you the currently logged in user.

You would need to initialize the user_id on creation to pass this test.

Stephan

current_user is provided by acts_as_authenticated through the
following method:

def current_user
@current_user ||= (session[:user] &&
User.find_by_id(session[:user])) || :false
end

Because of the sessions usage, I don’t think you want to use model
validation.

In the controllers you can do current_user.widgets.find() (instead of
just Widget.find() ) which will only bring up authenticated items,

thanks,
C.

On Dec 10, 2:47 pm, Stephan W. [email protected]

Charles wrote:

current_user is provided by acts_as_authenticated through the
following method:

def current_user
@current_user ||= (session[:user] &&
User.find_by_id(session[:user])) || :false
end

The implementation of this current_user method could be changed when the
notion of current-user changes. At the moment, it looks like the current
user is the one who is logged in through cookies/sessions, and the form
of the restriction being sought looks to me to go by the idea of a
“current user”.

I would prefer not having to remember to use the “current-widgets
finder”, when there is another way.

Stephan

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