我在两个模型之间有如下多对多关系:
#users.rb
has_many :users_to_roles
has_many :roles, through: :users_to_roles
#users_to_roles.rb
belongs_to :user
belongs_to :role
#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles
如果有“处于此角色”的用户,我想禁止删除角色。 Here我找到了两个应该做这项工作的人选:
:restrict_with_exception causes an exception to be raised if there are any associated records :restrict_with_error causes an error to be added to the owner if there are any associated objects
但没有关于此语法及其工作原理的示例。
你能帮忙让它生效吗:
#roles.rb
has_many :users_to_roles
has_many :users, through: :users_to_roles, dependent: restrict_with_exception
最佳答案
使用Callbacks 可以轻松完成此类操作.就我而言,我在我的模型中添加了以下方法:
# callbacks
before_destroy :check_for_users_in_this_role
def check_for_users_in_this_role
status = true
if self.security_users.count > 0
self.errors[:deletion_status] = 'Cannot delete security role with active users in it.'
status = false
else
self.errors[:deletion_status] = 'OK.'
end
status
end
关于ruby-on-rails-3 - 如果关联存在,如何禁止删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17380794/