Zab*_*bba 3 activerecord callback ruby-on-rails-3
我有一个简单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
Run Code Online (Sandbox Code Playgroud)
所以,事实证明这是另一个Rails的陷阱.
解决方案是移动before_destroy上面的has_many呼叫.
@Yves Senn,你是对的.从现在开始我会避开它.使用dependent: :restrict而不是dependent :destroy,在这种情况下,消除了我的before_destroy回调的需要.
| 归档时间: |
|
| 查看次数: |
895 次 |
| 最近记录: |