【问题标题】:Associations not loaded in before_destroy callbackbefore_destroy 回调中未加载关联
【发布时间】:2013-01-05 19:11:28
【问题描述】:

我有一个简单的User & Account 模型。如果帐户附加了用户,我想防止删除该帐户。我创建了一个User 和一个Account 并将它们关联起来。然后,我在控制台上执行Account.find(x).destroy。帐户被销毁!

注意事项:

  1. 用户的account_id是正确的。
  2. Account.find(x).users.empty? 在控制台返回 false
  3. Account.find(x).destroyable? 在控制台返回 true
  4. users.empty? in def destroyable? 返回 true !!

我做错了什么?这是什么?

代码(Ruby 1.9.2-p290 上的 Rails 3.2.9):

class User < ActiveRecord::Base
  belongs_to :account
end

class Account < ActiveRecord::Base

  has_many :users, dependent: :destroy
  attr_accessible :name
  before_destroy :destroyable?

  def destroyable?
    if users.empty? # This returns true when called via callback.
      true
    else
      false
    end
  end

end

【问题讨论】:

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


    【解决方案1】:

    所以,事实证明这是 Rails 的又一个陷阱。

    解决方案是将before_destroy 移到has_many 调用上方。

    @Yves Senn,你是对的。从现在开始我会避免它。 使用dependent: :restrict 而不是dependent :destroy,在这种情况下,我不需要我的before_destroy 回调。

    【讨论】:

    • 在过去的几天里,我处理了几个 Rails 错误,这些错误与您在模型中的定义顺序有关。我强烈建议将回调定义始终放在关联之后。
    【解决方案2】:

    我认为问题出在dependent: :destroy。如果您不想销毁关联用户的帐户,则不应添加依赖选项。

    这也是非常危险的,因为它可能会意外破坏用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多