Last Updated: February 25, 2016
·
830
· joshmcmillan

Easily determining ownership in Rails

Here's a really quick snippet I drop into user models which allows you to easily determine whether that particular user owns another model:

def owns?(model)
  !!(model.responds_to?(:user_id) && model.user_id == self.id)
end

Easy as cheese. Example usage:

u = User.new
f = Foo.new

u.owns?(f) # == true if f.user_id = u.id