Track dirty for not-persisted attribute in an ActiveRecord object in rails

前端 未结 4 1456
天命终不由人
天命终不由人 2021-02-05 03:27

I have an object that inherits from ActiveRecord, yet it has an attribute that is not persisted in the DB, like:

 class Foo < ActiveRecord::Base
   attr_acces         


        
4条回答
  •  不知归路
    2021-02-05 03:49

    I'm using the attribute_will_change! method and things seem to be working fine.

    It's a private method defined in active_model/dirty.rb, but ActiveRecord mixes it in all models.

    This is what I ended up implementing in my model class:

    def bar
      @bar ||= init_bar
    end
    def bar=(value)
      attribute_will_change!('bar') if bar != value
      @bar = value
    end
    def bar_changed?
      changed.include?('bar')
    end
    

    The init_bar method is just used to initialise the attribute. You may or may not need it.

    I didn't need to specify any other method (such as define_attribute_methods) or include any modules. You do have to reimplement some of the methods yourself, but at least the behaviour will be mostly consistent with ActiveModel.

    I admit I haven't tested it thoroughly yet, but so far I've encountered no issues.

提交回复
热议问题