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

前端 未结 3 719
陌清茗
陌清茗 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:09

    I took gayavat's answer and reworked it into my test_helper.rb file, because I didn't want to override the usual #reload method.

    class ActiveRecord::Base
      attr_accessor :default_instance_variables
      after_initialize do 
        @default_instance_variables = instance_variables
      end
    end
    def reload_ivars(obj)
      obj.reload
      obj.instance_variables.each do |ivar|
        if ivar == :'@default_instance_variables' || 
         obj.default_instance_variables.include?(ivar)
          next 
        end
        obj.send(:remove_instance_variable, ivar)
      end
    end
    

    When I need to reload something in a test I just call reload_ivars(object).

提交回复
热议问题