【问题标题】:duplicate rows in join table with three has_many :through associations具有三个 has_many 的连接表中的重复行:通过关联
【发布时间】:2014-02-19 17:16:27
【问题描述】:

说明

我有四个模型:

  1. 用户
  2. 组织结构
  3. 角色
  4. 组织用户角色

这个想法是一个用户可以属于多个组织并且可以具有多个角色,但每个组织只有一个。

我的模型如下所示:

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


    【解决方案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]
    

    我做了一个类似的应用程序,在我的数据库中有唯一的列,这个解决方案有效

    【讨论】:

      【解决方案2】:

      你需要 has_many 到 3 个表,看看这个链接:

      Rails 3 has_many through with 3 tables

      【讨论】:

        【解决方案3】:

        我最终按照这里的说明进行操作:

        How to join mutli-role, multi organisation tables in Rails

        它就像一个魅力。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-03
          • 2018-06-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多