【问题标题】:In Rails, how can I detect if a model is being changed via nested attributes vs. on its own?在 Rails 中,如何检测模型是通过嵌套属性还是通过自身更改?
【发布时间】:2022-06-17 00:23:59
【问题描述】:

假设我有一个模型 Checklisthas_many :itemsaccepts_nested_attributes_for :items

我想在某些 Item 回调和验证中知道它是通过嵌套属性更新还是单独更新。 (这可以让我在通过 Checklist 编辑多个项目时只运行一次某些挂钩来优化。)

如何检测到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    我发现了一个看起来不错的方法。

    我向 Item 添加一个标志,并覆盖 Checklist items_attributes= 以设置该标志。

    项目:

    class Item < ApplicationRecord
      # …
    
      attr_accessor :updated_via_checklist
    
      after_save do
        if updated_via_checklist
          # Do nothing. The Checklist does something in batch.
        else
          do_something
        end
      end
    end
    

    清单:

    class Checklist < ApplicationRecord
      # …
    
      def items_attributes=value)
        return_value = super
        items.each { _1.updated_via_checklist = true }
        return_value
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 2017-02-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      相关资源
      最近更新 更多