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. 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? Regards, Carl.
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
Hi,> I think you mean @list = List.find_first(@params[ "list" ][ "id" ])Yes, indeed I did - I typed in the code fresh into my mail client, rather than cut+paste!> And also in your case it would probably be clearer to do: > if list.owner == @session["user"] > rather than > if @session[ "user" ].lists.include? listYeah, I agree.> 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.Yes, that did help. I''ll just leave it as is (Except for the change above) then, I was just wondering if there was a better way than I was already doing it. Thanks for your help, Carl.