在我的应用中,我有用户,角色和权限。
当我删除角色时,我想删除在连接表中与该角色关联的所有用户和权限。 我不想删除用户或权限。
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => 'users_roles'
has_and_belongs_to_many :permissions, :join_table => 'roles_permissions'
end
查看文档,您可以使用:dependant
,但这也会破坏相关记录。但我只想破坏连接记录。
我在考虑做:
after_destroy :remove_associated_users
after_destroy :remove_associated_permissions
def remove_associated_users
connection = ActiveRecord::Base.connection
connection.execute("DELETE FROM users_roles WHERE role_id = " + self.id.to_s)
end
def remove_associated_permissions
connection = ActiveRecord::Base.connection
connection.execute("DELETE FROM roles_permissions WHERE role_id = " + self.id.to_s)
end
答案 0 :(得分:2)
我会使用has_many :though
而不是无模型的HABTM关系。
它有几个优点:
首先创建一个迁移,将表从users_roles
重命名为user_roles
,因为前者会导致rails找到Users::Role
。对权限连接表执行相同的操作。
class Role < ApplicationRecord
has_many :user_roles, dependent: :destroy
has_many :users, through: :user_roles
end
class UserRole < ApplicationRecord
belongs_to :user
belongs_to :role
end
class User < ApplicationRecord
has_many :user_roles, dependent: :destroy
has_many :roles, through: :user_roles
has_many :user_permissions, dependent: :destroy
has_many :permissions, through: :user_permissions
end
class UserPermission < ApplicationRecord
belongs_to :user
belongs_to :permission
end
class Permission
has_many :user_permissions, dependent: :destroy
has_many :users, through: :user_permissions
end
答案 1 :(得分:1)
您可以使用before_destroy回调
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => 'users_roles'
has_and_belongs_to_many :permissions, :join_table => 'roles_permissions'
before_destroy { users.clear }
before_destroy { permissions.clear }
end