Creating a portfolio on RoR
We have created a function that can hold a session by referring to Chapter 9 of the rails tutorial.
At that time, there was a code that I was interested in, so I would appreciate it if anyone could answer.

class User</pre>
<pre><code data-language = "User">def remember
    self.remember_token = User.new_token
    update_attribute (: remember_digest, User.digest (remember_token))

Regarding self.remember_token, there is a description in the tutorial that it will be a local variable unless self. Is added.
In my understanding, the attribute added by attr_accessor is associated with User, and if self. Is not added, Ruby cannot determine what the attribute is associated with, so I thought that I could not do what I expected. (The way of expression may be strange.)
Therefore, I summarized that the attribute cannot be accessed without writing self. Or (in this case) User.
At that time,

update_attribute (: remember_digest, User.digest (remember_token))

User.digest (remember_token) in the above code part
I thought that if I wrote it like this, I would go looking for the local variable remember_toekn, so I compared the operation with the case where I modified it as follows.

update_attribute (: remember_digest, User.digest (self.remember_token))

On the console, there was no change in behavior.

I was curious about the intention of posting the code without self. In the tutorial and asked.
(When passing an attribute as an argument, can self. be omitted?
If ruby ​​isn't in a local variable, do you go looking for another variable with the same name, regardless of the variable type? )


self.remember_token = User.new_token

This part is a setter method to remember_token, not an assignment,

update_attribute (: remember_digest, User.digest (remember_token))

Did you call the getter method here?

In this way of thinking, if you add self. When calling the setter method, and if you define it in the class when calling the getter method, self. Can be omitted, so can you call it as it is without self.?

Probably due to poor understanding of access methods, but I can't organize my mind (sorry)

  • Answer # 1

    [Setter method to remember_token, not assignment]
    This is true, but if you say so, there is no substitution in ruby, and somehow = is all a method.
    For example, in the database item of the User model, for example, email, email = is not an assignment but a method. (Because it is troublesome, let me express it as substitution here)

    No receiver is required for references to DB attributes and instance variables.
    A receiver is required for both assignments to DB attributes and instance variables.
    Personally, I don't think I should do something without it, but now it is.