user3399101
user3399101

Reputation: 1537

What does .self do in this context?

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

Answers (4)

KKB
KKB

Reputation: 558

self refers to the current instance of a model. It is use for call method and attributes for current model.

Upvotes: 3

Dave Newton
Dave Newton

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:

  1. Different than @user_id, and/or since this is tagged Rails, ...
  2. ...different than the attribute access "raw" via whatever underlying mechanism like 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

Severin
Severin

Reputation: 8588

.self is reffering to the object it is being called on.

Upvotes: 0

CWitty
CWitty

Reputation: 4536

This will refer to the model instance that this method is being called on.

Upvotes: 1

Related Questions