Recently watchingrailstutorial.
viarails g model User name:string email:string
The generated model gradually became the following virtues along with the tutorial:
class User < ApplicationRecord
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
#VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end
In this codeself.email
,email
as well as:email
What do you mean and what is the difference?
If you putvalidates :email, ...
insteadvalidates self.email, ...
After
Why is it reported?NoMethodError: NoMethodError: undefined method 'email'
?
before_save { self.email = email.downcase }
Here
self.email
A that represents the current objectemail.downcase
TheActiveRecord
Automatically generated for you);
This line of code means: oneUser
Before saving the instance object (before_save
),
Your question may be: when will you use it?self
When will you not use it?
Answer: Not in most casesself
, this kind of situation you encounter is the only one that needs to be displayed for use.self
The situation.
validates :email, ...
insteadvalidates self.email, ...
After
validates
Is a class macro (class macro
), in the class macroself
Represents the current class object itself (User
), the current classUser
Objects (class objects themselves) do notUser
There is an example methodActiveRecord
It is generated for you, as explained above), so report an error.
This line of code means: oneUser
Instance objectsave
Or ..update
Before, verification is requiredvalidates self.email, ...
On behalf of the verificationUser
Class object’s ownUser
Class objects themselves do notNoMethodError
.PS: It is suggested to read ruby Metaprogramming (the second edition of Chinese version has already been published), and you will have a more thorough understanding of Ruby’s essence. If you don’t know how to use many methods in Ruby, DHH’s recommended “The Ruby Way: Solutions and Techniques in Ruby Programming” is also a book by Gao Daquan. Pickaxe book “Programming ruby” and David Flanagan’s “The Ruby Programming Language” are also two very good Ruby full solutions (although these two books are outdated, they have no effect on you);