【发布时间】:2014-02-19 17:16:27
【问题描述】:
说明
我有四个模型:
- 用户
- 组织结构
- 角色
- 组织用户角色
这个想法是一个用户可以属于多个组织并且可以具有多个角色,但每个组织只有一个。
我的模型如下所示:
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
问题
Migrations 和 rake db:seed 运行成功,但随后表
organization_user_roles
每个用户包含重复的行:
第 1 行:User_id 1 -> Organization_id 1
第 2 行:User_id 1 -> Role_id 1
如何在一行中同时关联用户、组织和角色?
提前非常感谢,你们永远是一个了不起的帮助!
【问题讨论】:
标签: sql ruby-on-rails ruby