【问题标题】:Getting Previous object in Callbacks Rails在回调 Rails 中获取上一个对象
【发布时间】:2021-04-20 05:11:20
【问题描述】:
    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' 方法可用于获取以前的值,但这是模式函数的一个非常小的示例,我有很多字段和相关的记录依赖项。

【问题讨论】:

    标签: ruby-on-rails ruby object callback


    【解决方案1】:

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

    使用 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=方法,在你调用保存/更新的地方,在分配属性之前,调用example.old_mode = mode

    【讨论】:

    • 我试过了,效果很好,我现在将测试所有案例。谢谢!
    • 别担心,:)。
    猜你喜欢
    • 2012-04-21
    • 1970-01-01
    • 2019-04-17
    • 2016-01-27
    • 1970-01-01
    • 2019-10-25
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多