【发布时间】:2013-01-05 19:11:28
【问题描述】:
我有一个简单的User & Account 模型。如果帐户附加了用户,我想防止删除该帐户。我创建了一个User 和一个Account 并将它们关联起来。然后,我在控制台上执行Account.find(x).destroy。帐户被销毁!
注意事项:
- 用户的
account_id是正确的。 -
Account.find(x).users.empty?在控制台返回false -
Account.find(x).destroyable?在控制台返回true -
users.empty?indef 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