【问题标题】:Right association between three models三个模型之间的正确关联
【发布时间】:2014-02-17 11:39:24
【问题描述】:

我正在努力寻找关联三个模型的最简单解决方案:

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

用户和组织是一种 HABTM 关联 - 一个用户可以拥有多个组织,反之亦然。

一个用户也可以有多个角色,但每个组织只能有一个角色。

现在我的模型中有这个:

user.rb

class User < ActiveRecord::Base
  has_many :roles, through: :organizations
  has_and_belongs_to_many :organizations, :join_table => :organizations_users
end

organization.rb

class Organization < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => :organizations_users
  has_many :roles
end

role.rb

class Role < ActiveRecord::Base
  has_many :users, through: :organizations
  belongs_to :organizations
end

这有意义吗?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    这是我的:

    • 鉴于您正在使用 has_and_belongs_to_many 并给出 Rails 的默认值,您对 join_table 的规范是多余的
    • 只有在organizations 表中同时具有roleuser 字段时,您的has_many :roles, through: :organizations 才能工作,因为Rails 将期望对该表执行SQL select 来查找这些字段。

    由于您希望每个组织的用户最多拥有一个角色,那么我认为最直接的方法是将role 字段添加到organizations_users 模型中,如下所示:

    user.rb

    class User < ActiveRecord::Base
      has_many :roles, through: :organizations_users
      has_many :organizations, :through => :organizations_users
      has_many :organizations_users
    end
    

    organization.rb

    class Organization < ActiveRecord::Base
      has_many :users, :through => :organizations_users
      has_many :roles, :through => :organizations_users
      has_many :organizations_users
    end
    

    organization_user.rb

    class OrganizationUser < ActiveRecord::Base
      belongs_to :user
      belongs_to :organization
      belongs_to :role
    end
    

    role.rb

    class Role < ActiveRecord::Base
    end
    

    以上假设您有某些理由希望 Role 继续成为 ActiveModel 而不仅仅是 organizations_users 表中的字符串字段。

    【讨论】:

    • 完美,就像一个魅力!只有一个问题 - 当我用种子数据填充数据库时,现在有 4 个列(id、user_id、organization_id、role_id)的 organizations_users 表为每个关联创建单独的条目,例如用户 1 - 组织 1用户 1 - 角色 1 而不是 用户 1 - 组织 1 - 角色 1 。有什么建议可以解决吗?
    • 您是如何创建条目的?如果您通过 has_many 辅助方法 other 而不是 organizations_users 进行分配,就会发生这种情况,因为其他辅助方法只知道两个元素之间的关联。
    • 这很有意义......现在我正在尝试在控制台中使用此代码创建一个新用户:OrganizationUserRole#create_user(email: 'thomas@aquarterit.com', password: 'password')(而不是用户 OrganizationUser,我现在使用模型 OrganizationUserRole。应该选择更短的东西......无论如何)。结果是=&gt; OrganizationUserRole(id: integer, user_id: integer, organization_id: integer, role_id: integer) - 我仍然做错了,但我只是不知道是什么
    • 参见guides.rubyonrails.org/… 以了解create_association 方法的描述(即在您的情况下为create_user)。它应该创建一个新的用户实例并在您调用create_user 方法的对象中设置user_id 的值。但是,# 在 Ruby 中是一个注释字符,因此之后的所有内容都会在 Rails 控制台中被忽略,因此您只是得到了 OrganizationUserRole 常量的打印输出。
    • 谢谢!您的回答为我指明了正确的方向。我按照这里的说明进行操作:stackoverflow.com/questions/16771503/…,它就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多