我正在尝试创建一个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来查询数据。
编辑:决定不这样做,并试图找出一种不同的方法。
答案 0 :(得分:1)
我会用间接关系设置它:
class User
has_many :employments
has_many :companies, through: :employments
has_many :positions
has_many :teams, through: :positions
end
class Company
has_many :employments
has_many :users, through: :employments
has_many :teams, through: :users
end
class Team
has_many :positions
has_many :users, through: :positions
has_many :companies, through: :users
end
# join model between User and Company
class Employment
belongs_to :user
belongs_to :company
end
# join model between User and Team
class Position
belongs_to :user
belongs_to :team
end
虽然您可能使用单一的3方式连接模型,但这违反了单一责任原则,并且没有很好地映射域。
3路连接引入了相当多的复杂性,因为您不能通过删除连接表中的行来简单地取消链接两个记录。并且ActiveRecord不会自动跟踪外键列。
如果要为此数据模型添加角色,可以采用以下几种方法:
# join model between User and Team
class Position
enum role: [:grunt, :supervisor]
belongs_to :user
belongs_to :team
end
class User
has_many :user_roles
has_many :roles, through: :user_roles
def has_role?(name, resource = nil)
roles.exists?(name: name, resource: resource)
end
end
class Role
belongs_to :resource, polymorpic: true, optional: true
has_many :user_roles
end
class UserRole
belongs_to :user
belongs_to :role
end
这是一个非常灵活的系统,允许您将角色附加到任何事物 - 公司,团队等。并且允许您构建系统,其中角色甚至可以由最终用户定义。查看rolify gem以获取完整示例。