因此,我在用户和考试之间建立了多对多的关系,使用权限作为中间表。
我想为管理员创建一个表,以授予对不同测试的不同级别的访问权限。
那么,是否有更好的方法来创建新的Permission记录,而不是遍历所有尚未绑定到此用户并创建新权限的考试?
注意,部分或全部考试可能已经与用户联系在一起。
答案 0 :(得分:0)
假设你有类似的东西:
class User < ActiveRecord::Base
has_many :permissions
has_many :exams, through: :permissions
end
class Exam < ActiveRecord::Base
has_many :permissions
has_many :users, through: :permissions
end
class Permission < ActiveRecord::Base
belongs_to :user
belongs_to :exam
end
你可以这样做:
user = User.find(1)
if user.exams.where(id:foo).length==0
Permission.create(user_id:1, exam_id0:foo, access_level:bar)
else
user.permissions.where(exam_id:foo).first.update_attribute(:access_level,bar)
end
假设您正常构建关系(权限中user_id
和exam_id
上有索引),它将加入表并确定权限是否已经非常快速地存在。