【问题标题】:Why relative position of associations and callbacks in a rails model affecting the results为什么rails模型中关联和回调的相对位置会影响结果
【发布时间】:2014-02-09 22:30:12
【问题描述】:

我有一个模型 Indent,它有很多 indent_items 并且通过 indent_items 有很多发货。

class Indent < ActiveRecord::Base

  before_destroy :check_for_shipments # WORKS HERE

  has_many :indent_items, inverse_of: :indent, :dependent => :destroy
  has_many :shipments, :through => :indent_items

  # before_destroy :check_for_shipments # DOESN"T WORK HERE

  private
  def check_for_shipments
   # Should not be allowed to delete if there are any shipments.
   if self.shipments.count > 0
     errors.add(:base, "Cannot delete indent because shipments are there.")
     return false
   end    
  end

end

我猜这可能是因为如果在关联之后提到回调,所有缩进项都被标记为删除,并且发货计数检查总是返回零。

但这不应该发生。或者我可能在这里遗漏了一些东西。我不知道。

我正在使用 Rails 3.2.8。

【问题讨论】:

  • 我不认为订单应该有所作为。尝试创建一个独立的 gist 来重现错误:edgeguides.rubyonrails.org/…
  • 好的。很快就会这样做。

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2


【解决方案1】:

这是 rails 的期望行为,如果您希望在货物销毁之前执行 before_destroy 回调(因为 dependent: :destroy 选项),那么您必须在 before_destroy 回调上使用 prepend 选项。

例如

class Indent < ActiveRecord::Base

  has_many :indent_items, inverse_of: :indent, :dependent => :destroy
  has_many :shipments, :through => :indent_items

  before_destroy :check_for_shipments, prepend: true #this will work

  private

  def check_for_shipments
   # Should not be allowed to delete if there are any shipments.
   if self.shipments.count > 0
     errors.add(:base, "Cannot delete indent because shipments are there.")
     return false
   end    
  end

end

如需进一步参考,您可以阅读from here

【讨论】:

  • 谢谢,您的回答解决了我眼前的问题。但问题仍未解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 2013-05-28
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多