3

我有一个简单的模型UserAccount如果帐户附加了用户,我想防止删除该帐户。我创建一个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?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
4

2 回答 2

7

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

解决方法是移动before_destroy上面的has_many调用。

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

于 2013-01-05T19:30:17.340 回答
1

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

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

于 2013-01-05T19:23:09.107 回答