【问题标题】:Rails, polymorphic association. Destroy with "touch: true", useless stepsRails,多态关联。用“touch: true”销毁,没用的步骤
【发布时间】:2018-07-15 04:05:25
【问题描述】:

我在 Rails 5 上。

我有一个这样的多态关联:

models/enjoy_level.rb

class EnjoyLevel < ApplicationRecord
  belongs_to :enjoyable, polymorphic: true, touch: true, optional: true
end

models/mother.rb

class Mother < ApplicationRecord
  has_one :enjoy_level, as: :enjoyable, dependent: :destroy

  accepts_nested_attributes_for :enjoy_level
end

如果我销毁一个mother(有touch: true 选项)它仍然:

  • 销毁之前的enjoy_level
  • Motherupdate_at设置为now();
  • 最后销毁这个Mother记录一。

第一步和第二步都没用,对吧?

我哪里错了?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5 rails-activerecord


    【解决方案1】:

    来自http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

    :touch - 如果为 true,则关联对象将被触摸( updated_at/on 属性设置为现在)保存此记录时 或销毁。如果您指定一个符号,该属性将被更新 除了 updated_at/on 属性之外,还有当前时间。

    因此,当您销毁 mother 时,您首先调用的是 dependent: destroy 依赖项,这是您的 enjoy_level 对象,因为它们有 touch: true,您正在触摸 mother 对象(因为它也在销毁时更新它)。 因此,在当前情况下,第二个查询可能没用,但它们按计划工作。

    【讨论】:

    • 你是说我的流程是正确的吗?这是 Rails 的发展方向吗?我错了吗?
    • @JohnSam Rails 会这样,因为你已经这样编程了。您可以删除touch: true,您将不会有第二次查询,它会更有意义。
    • 但是我需要它,因为我需要在编辑的时候更新 updated_at 列... 怎么办?
    • @JohnSam 好吧,在这种情况下,如果您不想在销毁时进行其他更新查询,删除 touch: true 选项并进行回调会更容易:before_update
    【解决方案2】:

    您可以在销毁父对象时在 ActiveRecord 级别禁用触摸:

    ActiveRecord::Base.no_touching do
      mother.destroy
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多