在回调中获取上一个对象 Rails

Getting Previous object in Callbacks Rails

    before_save
     old_mode = previous_instance.mode
     new_mode = new_instance.mode

     if old_mode != new_mode 
        do_something
     end

    end
    
    def mode

      if field1 == 'something' && field2 == 'otherthing'
       return 'mode1'
      end
      
      if field3 == 'something' && associated_record.field == 'anyotherthing'
        
        return 'mode2'
      end
    end
  
  if field3 == 'something' && associated_record.field == 'anyotherthing'
    
    return 'mode2'
  end
end

我想调用上一个实例的实例方法,回调一个新实例,怎么办?正如您在代码中看到的,该方法是根据字段和关联的记录字段值计算模式,我想获得以前的模型和新模式。我知道 '_was'/'changes' 方法可用于获取以前的值,但这是模式函数的一个非常小的例子,我有很多字段和关联的记录依赖项。

不确定这是否正确,但应该可行。

使用attr_accessor, 例如:

class Example

  attr_accessor: old_mode

  before_save
    if old_mode && old_mode != mode 
      do_something
    end
  end
  
  def attributes=(attribs)
    @old_mode = mode
    super
  end
    
  def mode
    do_calculation
  end
end

或者你可以不使用 attributes= 方法,在你调用 save/update 的地方,在分配属性之前,调用 example.old_mode = mode