我有四种模式:
这个想法是,一个用户可以属于许多组织,可以拥有多个角色,但每个组织只有一个。
我的模特看起来像这样:
user.rb
class User < ActiveRecord::Base
has_many :roles, :through => :organization_user_roles
has_many :organizations, :through => :organization_user_roles
has_many :organization_user_roles
end
organization.rb
class OrganizationUserRole < ActiveRecord::Base
has_many :organization_user_roles
has_many :users, :through => :organization_user_roles
has_many :roles, :through => :organization_user_roles
end
role.rb
class Role < ActiveRecord::Base
end
organization_user_role.rb
class OrganizationUserRole < ActiveRecord::Base
belongs_to :user
belongs_to :organization
belongs_to :role
end
我正在使用以下种子播种我的数据库.rb
require 'faker'
# seed with standard roles
role_list = [
[ "superadmin" ],
[ "admin" ],
[ "user" ],
[ "owner" ],
]
role_list.each do |role|
Role.create( :name => role[0] )
end
# create default superadmin & organization
p = User.create(email: 'thomas@aquarterit.com', password: 'password')
o = Organization.create(name: 'A Quarter IT', website: 'www.aquarterit.com')
o.users << User.find_by_email('thomas@aquarterit.com')
p.roles << Role.find_by_name("superadmin")
# 30 organizations, 3 users each
30.times do |organization|
o = Organization.create(name: Faker::Company.name, website: Faker::Internet.domain_name)
3.times do |user|
p = User.create(email: Faker::Internet.email, password: 'password')
p.roles << Role.find_by_name("user")
o.users << User.last
end
end
迁移和rake db:seed运行成功,但之后是表
organization_user_roles
每个用户包含重复的行:
第1行:User_id 1 - &gt; Organization_id 1
第2行:User_id 1 - &gt; Role_id 1
如何将用户,组织和角色同时关联在一行?
提前多多感谢,你们总是一个惊人的帮助!
答案 0 :(得分:1)
您需要为三个参数添加数据库唯一键,例如
add_index "organization_user_roles", ["user_id", "organization_id", "role_id"], name: "unique_roles", unique: true, using: :btree
然后在您的organization_user_role模型中
validates_uniqueness_of :role_id, scope: [:user_id, :organization_id]
我在我的数据库中使用了独特的列做了类似的应用程序,这个解决方案正常工作
答案 1 :(得分:1)
你需要has_many通过3个表,看看这个链接:
答案 2 :(得分:0)