Reputation: 1537
So, I'm working on a project and I have no idea as to what the self. does in this context:
def owner_is?(user)
self.user_id == user.id
end
I understand what def self.method does, as it's a class method but not how it's used above.
Why might someone use self.user_id like in the context above, what is that doing? My guess is, self is referring to the current_user?
Please help clear this up for me,
Thanks!
Upvotes: 0
Views: 119
Reputation: 558
self refers to the current instance of a model. It is use for call method and attributes for current model.
Upvotes: 3
Reputation: 160191
self
refers to the current instance of whatever you're looking at.
Here it calls the instance's user_id
method, which might be:
attributes[sym]
, bypassing the generated or your own accessors.Is it a significant difference? It really depends. The safest bet is to prefix persisted field accessors with self
to ensure you're getting what you think you are, particularly if you override any of those accessors.
I don't always do this when it's not an assignment, but there is an associated risk.
Upvotes: 3
Reputation: 4536
This will refer to the model instance that this method is being called on.
Upvotes: 1