【问题标题】:Rails 5 dependent: :destroy doesn't workRails 5 依赖: :destroy 不起作用
【发布时间】:2016-06-08 14:43:05
【问题描述】:

我有以下课程:

class Product < ApplicationRecord
  belongs_to :product_category

  def destroy
    puts "Product Destroy!"
  end

end

class ProductCategory < ApplicationRecord
  has_many :products, dependent: :destroy

  def destroy
    puts "Category Destroy!"
  end
end

在这里,我试图覆盖我最终想要这样做的destroy方法:

update_attribute(:deleted_at, Time.now)

当我在 Rails 控制台中运行以下语句时:ProductCategory.destroy_all 我得到以下输出

Category Destroy!
Category Destroy!
Category Destroy!

注意:我有三个类别,每个类别都有多个产品。我可以通过ProductCategory.find(1).products 确认它,它返回一个产品数组。我听说 Rails 5 中的实现发生了变化。关于如何让它工作的任何要点?

编辑

我最终想要的是一次性软删除一个类别和所有相关产品。这可能吗?还是会在销毁回调之前迭代每个 Product 对象? (我的最后一个选择)

【问题讨论】:

  • 删除你的两个销毁方法,然后再试一次。
  • 在我看来,您正在覆盖 active_model 销毁方法,并且您应该在销毁中调用“super”?
  • 我真的不建议覆盖 ActiveRecord 方法。让你自己喜欢 update_as_destroyedupdate_as_destroyed_all 而不是覆盖现有的。
  • 听起来你想要“软删除”。 stackoverflow.com/questions/23017070/…
  • 是的,我已经编辑了我的问题。

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


【解决方案1】:

你应该从你的destroy方法中调用super:

def destroy
  super 
  puts "Category destroy"
end

但我绝对不建议您覆盖活动模型方法。

【讨论】:

  • 从他的问题来看它不起作用,因为记录仍然会被破坏。他不想要那个
  • 是的,这就是他想要做的,但我的回答是指他的问题,即为什么依赖: :destroy 不起作用。他不是在问如何实施他想做的更新。
【解决方案2】:

所以我最后是这样做的:

class Product < ApplicationRecord
  belongs_to :product_category

  def destroy
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end

end

class ProductCategory < ApplicationRecord
  has_many :products, dependent: :destroy

  def destroy
    # run all callback around the destory method
    run_callbacks :destroy do
      update_attribute(:deleted_at, Time.now)
      # return true to escape exception being raised for rollback
      true
    end
  end
end

我从销毁返回 true 确实使 update_attribute 有点危险,但我也在 ApplicationController 级别捕获异常,所以对我们来说效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2016-06-19
    • 1970-01-01
    • 2019-09-20
    • 2016-10-23
    相关资源
    最近更新 更多