In the Michael Hartl tutorial, chapter 8, we set up the sign in page and create a new column in the database to hold a base 64 string. In the tutorial it's called a remember_token. In the user.rb:
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
self has a property called remember_token? Is this already built in or did it get created elsewhere? Maybe I'm just not understanding this very well.
He writes:
Because of the way Active Record synthesizes attributes based on database columns, without self the assignment would create a local variable called remember_token, which isn’t what we want at all. Using self ensures that assignment sets the user’s remember_token so that it will be written to the database along with the other attributes when the user is saved.
I'm confused, how did the user get a remember token? How does it know to write this to the database in that particular column?
In the user.rb you have the following code:
attr_accessible :name, :email, :password, :password_confirmation
There's nothing about remember_token there. How does it know to include this at User.save?
In this context, self
is a User object, and it has a remember_token
attribute because of the database column created by the migration in Section 8.2.1 of the Ruby on Rails Tutorial. (Prepending self
is necessary to assign to the attribute; without self
, Ruby would just create a local variable called remember_token
.)