The question is in regard to the Rails tutorial . In particular I have a doubt about listing 6.23 , this line:
before_save { |user| user.email = email.downcase }
I am curious about the variable "email" - where does it come from? Is it some kind of short Ruby syntax to call the left-hand side variable? Or does it call to the model's attribute (it would make passing the block variable redundant though)?
I'd appreciate anyone ridding me of my confusion.
Yes, you can omit passing the user to the block
before_save { self.email = email.downcase }
I personally prefer not using blocks and write named methods for this
before_save :reformat_email
private
def reformat_email
self.email = email.downcase
end
This is only valid if user
in the example is the same as self
AND regarding the example with using before_save in an ActiveRecord::Base class
email
is short for user.email
, but when assigning a value you can't use email =
, you must do user.email =
otherwise you will only assign to a local variable.
The example is changing what's in user.email
to user.email.downcase
And I think that when you use a before_save
with an argument it will be self
in that argument
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.