gpt4 book ai didi

ruby-on-rails - has_one 和belongs_to 与同一张表的关联

转载 作者:行者123 更新时间:2023-12-03 15:57:44 24 4
gpt4 key购买 nike

我想知道同一张 table 有 2 个关联是否可以。例如:

class CreateTeams < ActiveRecord::Migration[6.0]
def change
create_table :teams do |t|
t.string :name, null: false
t.references :manager, foreign_key: { to_table: 'users' }
end
end
end

class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :name, null: false
t.references :team
end
end
end

class Team < ApplicationRecord
has_many :users
belongs_to :manager, class_name: 'User', foreign_key: 'manager_id'
end

class User < ApplicationRecord
belongs_to :team
has_one :child_team, class_name: 'Team' # bad name, but just for example
end

或者创建一个带有team_id、user_id和member_type的连接表会更好?

Ruby/Rails 版本无关紧要,但我们假设 Ruby 是 2.7.0,Rails 是 6.0.0

最佳答案

从技术角度来看 - 这完全没问题,但要小心将来可能出现的外键循环。

这更多是一个架构问题以及您对系统将如何发展的预测。具有显式连接模型的多对多关系更加灵活。例如:

  • 经理总是属于团队吗?使用连接表可以更轻松地获取“团队中的所有用户,无论角色如何”或“一个人与之相关的所有团队,也无论角色如何”
  • 如果有其他角色或多个人在同一个位置-加入表也会派上用场
  • 关于ruby-on-rails - has_one 和belongs_to 与同一张表的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60306958/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com