Models don't have access to the session, so session[:user_id] is nil.
Sessions are a controller thing. One way I've seen this work is this:
1. Add a 'current_user' class property to your User model
2. Create a before_filter that sets this to the session[:user] on every
request (not just at login)
3. In your model code, use 'User.current_user' instead of session[:user]
I wouldn't even take the callback/filter route. I'd simply define my
own method, destroy_as:
<code>
class SomeModel < ActiveRecord::Base
def destroy_as(user)
return false unless self.user == user
destroy
end
end
# now the controller - presumably you
# have access to the user object, not just
# the id - i usually instantiate a user from
# an id in the session using a before_filter
def destroy
@obj = SomeModel.find(params[:id]
if @obj.destroy_as(@current_user)
flash[:notice] = 'It worked!'
else
flash[:error] = 'It didnt work!'
end
end
Hope that helps. You could alternatively just pass in the user ID to
destroy_as and do the comparison that way but I think this is more
intention revealing.