【发布时间】:2017-06-10 09:43:56
【问题描述】:
我正在尝试创建一个 4 路连接表。
class User < ApplicationRecord
has_many :user_configurations
has_many :teams, through: :user_configurations
has_many :companies, through: :user_configurations
scope :supervisors, -> { joins(:user_configurations).where(user_configurations: { supervisor: true }) }
scope :agents, -> { joins(:user_configurations).where(user_configurations: { supervisor: false }) }
end
class Team < ApplicationRecord
has_many :user_configurations
has_many :users, through: :user_configurations
belongs_to :company_unit
end
class CompanyUnit < ApplicationRecord
has_many :user_configurations
has_many :users, through: :user_configurations
has_many :teams
belongs_to :company
end
class Company < ApplicationRecord
has_many :user_configurations
has_many :users, through: :user_configurations
has_many :company_units
has_many :teams, through: :company_units
end
class UserConfiguration < ApplicationRecord
belongs_to :user, optional: true
belongs_to :team, optional: true
belongs_to :company, optional: true
#supervisor:boolean in this table
end
当我创建时,我会在 UserConfiguration 表中获得 2 个单独的条目。
Company.first.users.create(team_ids: [1])
id: 1, user_id: 1, team_id: nil, company_id: 1
id: 2, user_id: 1, team_id: 1, company_id: nil
我不知道尝试这样的事情是否是一种好习惯,任何建议都会非常有帮助,谢谢。每次搜索都会尝试执行 sql join 来查询数据。
编辑:决定不这样做,并将尝试找出不同的方法。
【问题讨论】:
-
你的例子的商业模式是什么?因为你的模型看起来很混乱!
-
我添加了公司团队关系。我希望能够让用户属于团队和公司,以便我可以删除用户团队但仍将其链接到公司。
标签: mysql ruby-on-rails ruby has-many-through