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

前端 未结 2 1478
一向
一向 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.

提交回复
热议问题