[Rails] Validation question
Tim Lucas
t.lucas at toolmantim.com
Wed Mar 2 12:52:05 GMT 2005
On 02/03/2005, at 10:46 PM, carl wrote:
> Hi all,
>
> I have something like this :
>
> user has_many lists
> list has_many items
>
> I want to validate that the currently logged-in user is the owner of
> the list an item is being added to. I can do it in "item/create" by
> doing something like :
>
> class item
> def create
> @list = List.new( @params[ "list" ][ "id" ] )
> if @session[ "user" ].lists.include? list
> ## OK
> else
> ## Not OK
> end
> end
> end
>
> and it works well enough.
>
I think you mean @list = List.find_first(@params[ "list" ][ "id" ])
And also in your case it would probably be clearer to do:
if list.owner == @session["user"]
rather than
if @session[ "user" ].lists.include? list
... assuming you have a belongs_to user called "owner" in your list
model object.
> However, is this considered the best way of doing this? I think that
> using validate() or one of the callback methods would be a neater way
> of doing it. Any suggestions?
You wouldn't want your model to access the session variable directly,
and you wouldn't neccessarily want to pass in the logged in user to
each model call, so I think the controller is the best place to put it.
Most you could do is probably add a method to your model called
ownedBy?, and instead of:
list.owner == @session["user"]
do a:
list.ownedBy? @session["user"]
but im not convined it is worth the effort.
HTH
- tim lucas
More information about the Rails
mailing list