Ruby on Rails model has email attribute, so self.email: what is the difference between email and email?

  question, ruby

Recently watchingrailstutorial.
viarails g model User name:string email:stringThe 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,emailas well as:emailWhat 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 }

Hereself.emailA that represents the current objectemailAttributes;email.downcaseTheemailRepresents calling an email method (ActiveRecordAutomatically generated for you);
This line of code means: oneUserBefore saving the instance object (before_save),emailConvert to lowercase;
Your question may be: when will you use it?selfWhen 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.selfThe situation.

  • validates :email, ...insteadvalidates self.email, ...After

validatesIs a class macro (class macro), in the class macroselfRepresents the current class object itself (User), the current classUserObjects (class objects themselves) do notemailMethod (current classUserThere is an example methodemailYesActiveRecordIt is generated for you, as explained above), so report an error.
This line of code means: oneUserInstance objectsaveOr ..updateBefore, verification is requiredemailAttributes; If changed tovalidates self.email, ...On behalf of the verificationUserClass object’s ownemailMethod, due toUserClass objects themselves do notemailMethod, soNoMethodError.

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);