Reputation: 3083
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?
Upvotes: 1
Views: 1427
Reputation: 3628
As of 2018, @remember_token
has an accessor method.
https://www.railstutorial.org/book/advanced_login#code-user_model_remember
class User < ApplicationRecord
attr_accessor :remember_token
before_save { self.email = email.downcase }
...
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
...
There is no remember_token
column in the database. It is a 'virtual' attribute. The remember token is stored as a hash as remember_digest
instead.
Upvotes: 0
Reputation: 1931
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
.)
Upvotes: 1