【发布时间】:2016-05-23 10:51:54
【问题描述】:
我在ProductUser 模型上有一个role 属性。用户可以通过owner(角色)删除,我想确保所有者在product 存在时不能删除自己。但是,当product 被删除时,所有product_users 都应该消失,包括所有者。
当我尝试删除product 时,以下代码会引发ActiveRecord::RecordNotDestroyed - Failed to destroy the record 错误。我猜这是因为dependent: :destroy 导致的执行顺序。我怎样才能做到这一点?
class ProductUser < ActiveRecord::Base
belongs_to :user
belongs_to :product, touch: true
before_destroy :check_for_owner
def check_for_owner
if product && role == "owner" #If I use simply: if role == "owner", it still doesn't work.
errors[:base] << "Owner can't be deleted!"
return false
end
end
end
class Product < ActiveRecord::Base
has_many :product_users, dependent: :destroy
....
end
【问题讨论】:
标签: ruby-on-rails validation activerecord callback