ruby-on-rails-3 - 如果关联存在,如何禁止删除

标签 ruby-on-rails-3 activerecord dependencies model-associations

我在两个模型之间有如下多对多关系:

#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/

相关文章:

ruby-on-rails - 尝试将UserMailer包含到我的 Controller 中时出现语法错误

gcc - 如何使用 binutils 链接器处理静态库之间的递归依赖关系?

arrays - 在其上应用事件记录 "where"时保持原始数组顺序

ruby-on-rails - 通过关联的属性值对集合进行排序的数据库查询

ruby-on-rails - 如果 Rails 查询中存在关联,则包含关联

java - Mac 上缺少 spring-boot-starter-web hibernate-validator 依赖项

c++ - 将所有项目依赖项放入项目存储库中是好习惯吗?

ruby-on-rails-3 - Rails 3 polymorphic_path-如何更改默认的route_key

ruby-on-rails - 你如何让一个对象观察/订阅自己来观察某个领域?

ruby-on-rails - Rails 3.1 include_root_in_json