Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

ruby on rails - Why do ActiveRecord callbacks require instance variables or instance methods to be prefixed with self keyword?

ActiveRecord has a few different callback methods used to simplify model logic. For example after_find and before_create methods.

Consider this code example:

class ExternalPrintingCard < ActiveRecord::Base
  belongs_to :user
  belongs_to :ph_user

  after_create :change_pin

  def change_pin
    self.user.randomize_printer_pin
  end

  def after_find
    return if self.card_status == false
    self.card_status = false if self.is_used_up?
    self.card_status = false if self.is_expired?
    self.save!
  end
end

If I remove all the self prefixes from the instance variables or instance methods, these 2 callbacks will be called, but it is as if they are local variables inside these callback methods.

This instance variable (card_status), instance methods (save!, is_used_up? and is_expired?) and association (user) worked fine outside these 2 callback methods without the self prefix.

The sample code in the Rails' documentation for callback methods (instance methods), seems to always use the self prefix even though it is calling instance variables or methods, which by right they are accessible without the self prefix normally.

I hope someone with a better understanding of ActiveRecord callbacks can help to shed a light on this behaviour.

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Technically you only need to use the self in front of the assignment methods. This is necessary to differentiate between a instance method with trailing = and an assignment to a local variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...