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

前端 未结 4 1500
天命终不由人
天命终不由人 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 04:08

    Write the bar= method yourself and use an instance variable to track changes.

    def bar=(value)
      @bar_changed = true
      @bar = value
    end
    
    def bar_changed?
      if @bar_changed
        @bar_changed = false
        return true
      else
        return false
      end
    end
    

提交回复
热议问题