【问题标题】:Rollback update_attributes in before_update在 before_update 中回滚 update_attributes
【发布时间】:2015-06-24 13:47:25
【问题描述】:

我有以下型号:

class Model < ActiveRecord::Base
    attr_accessible :foo

    before_update :check_for_stuff

    def check_for_stuff
      # foo_was = 42; foo = 24
      raise ActiveRecord::Rollback if foo_was == 42
    end

    def update_foo
      update_attributes foo: 24
    end
end

将引发异常,但不会发生回滚,该值将设置为 24。

如何正确触发整个事务的回滚?

【问题讨论】:

    标签: ruby-on-rails activerecord model


    【解决方案1】:

    如果 foo 的值是 42,你可以重置它。

    class Model < ActiveRecord::Base
      attr_accessible :foo
    
      before_update :check_for_stuff
    
      def check_for_stuff
        # foo_was = 42; foo = 24
        if foo_was == 42
          reset_attributes(["foo"]) # This resets just foo. Use reset_attributes to wipe all dirty changes.
          raise ActiveRecord::Rollback
        end
      end
    
      def update_foo
        update_attributes foo: 24
      end
    end
    

    有关reset_attributes 和ActiveModel::Dirty 接口here 的更多信息。

    【讨论】:

    • 编辑了我的问题,reset_attributes 可以解决问题,但实际上我需要回滚整个事务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多