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

前端 未结 2 1468
一向
一向 2020-12-15 05:33

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

Consider

相关标签:
2条回答
  • 2020-12-15 05:48

    Nasmorn is correct.

    ActiveRecord::Base placed all the column names inside @attributes instance variable (Hash) and create accessors instance methods for those column names.

    For example:

    card_status is a column in external_printing_cards table, it will have accessor methods with the name card_status and card_status=

    Since ruby local variable definition is dynamic, the line

    def after_find
      ....  
      card_status = false if self.is_used_up?
      ....
    end
    

    will mean we are defining and assigning to a local variable card_status rather than the instance method card_status=

    The article that Peer Allan posted provides more explanation on this.

    0 讨论(0)
  • 2020-12-15 06:02

    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.

    0 讨论(0)
提交回复
热议问题