我有一个简单的模型User。Account如果帐户附加了用户,我想防止删除该帐户。我创建一个User和一个Account并将它们关联起来。然后,我Account.find(x).destroy在控制台上做。账号被销毁!
笔记:
- 用户
account_id是正确的。 Account.find(x).users.empty?在控制台返回falseAccount.find(x).destroyable?在控制台返回trueusers.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