In Chapter 9 of the Rails tutorial, when creating a Remember Me function for implementing login function, there is "Automatically handle password column as a virtual attribute...", and "For that, use attr_accessor, Implement the user.remember_token method so that it can be used...", and the following code is described, but I do not understand why it becomes such code.

attr_accessor :remember_token
def remember
  self.remember_token = User.new_token
  update_attribute(:remember_digest, User.digest(remember_token))

○ Unclear point.

・Why is there a virtual attribute to create a remember method?
・In the first place, what are virtual attributes?

○ What I tried to solve → I checked attr_accessor
(Interpreted to change the instance variable so that it can be operated, but is it possible to create virtual attributes?)

I think this is a basic content, but I would appreciate it if you could teach me.
We apologize for the inconvenience, but we would appreciate your favor.

  • Answer # 1

    I haven't seen the tutorial
    "There is a place to enter the password on the Remember Me screen."
    I will write on the assumption that it will be.
    There is no password item in the users table of the database, and it is designed to put the encrypted password in _password and _password somehow. In order to enter it encrypted, there is a mechanism behind it so that if you put a password in user.password and save it, it will be OK.

    For this reason, it is necessary to have a mechanism to set password for user,
    about it. It doesn't matter if it's virtual (not in the database) or real (for the trick).

    So, attr_accessor, the attribute is the same (like) mechanism, so that the program can access various attributes such as email with user.email or user.email= (by defining methos of). , No change for ruby ​​program

    Oops, omission

    "There is a place to enter the password on the Remember Me screen."
    The assumption that

    When params.permit(:password) is used, an error will occur if there is no password= method. Therefore, temporary attribute definition is required.

Related articles