Is there a clean API for resetting instance variables on 'reload' in ActiveRecord?

前端 未结 3 693
陌清茗
陌清茗 2021-01-07 22:23

In an ActiveRecord::Base model, I can reset the state of the model to what it was when I got it from the database with reload, as long as the attri

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 23:07

    ActiveRecord does not provide a way to do this, it can only acts on the model attributes.

    That being said, I think a more elegant way to do it would be to loop over the ivars and set them to whatever you like :

    class User < ActiveRecord::Base
      def reload(options = nil)
        super
        self.instance_variables.each do |ivar|
          next if ivar == '@attributes'
          self.instance_variable_set(ivar, nil)      
        end
      end
     end
    

    Note that we skip @attributes because AR is taking care of it when you reload the attributes.

提交回复
热议问题