将ActiveRecord设置为两个字段,每个字段引用同一张表

问题描述 投票:0回答:3

我有一个Player类,我想拥有high_school_teamclub_team属性。因此,我认为Player将具有指向相应团队的high_school_team_idclub_team_id属性。我尝试在以下迁移中执行此操作,但是它不起作用。

class CreatePlayers < ActiveRecord::Migration[6.0]
  def change
    create_table :players do |t|
      t.string :first_name
      t.string :middle_name
      t.string :last_name
      t.decimal :height
      t.decimal :weight
      t.date :birthday
      t.references :team, :high_school_team, foreign_key: true
      t.references :team, :club_team, foreign_key: true
      t.decimal :gpa
      t.string :class_year
      t.string :intended_major
      t.string :email
      t.string :phone_number
      t.text :notes

      t.timestamps
    end
  end
end

它出现以下错误:

code/scout-db [master●] » rails db:migrate
== 20191218003854 CreatePlayers: migrating ====================================
-- create_table(:players)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

you can't define an already defined column 'team_id'.
/Library/Ruby/Gems/2.6.0/gems/activerecord-6.0.2.1/lib/active_record/connection_adapters/abstract/schema_definitions.rb:372:in `column'
...

[HighSchoolTeamClubTeam是使用Team进行单表继承的模型。

我不明白为什么会出现错误。 docs似乎说t.referenes的第一个参数是table_name,第二个ref_name:team是表的名称,我希望引用为high_school_team_idclub_team_id

当我将参数的顺序切换为t.references时,它仍然不起作用。它以某种方式给出相同的错误:you can't define an already defined column 'team_id'.

ruby-on-rails rails-activerecord
3个回答
0
投票

这里是您如何声明是否要在具有“两个名字”关系的玩家模型和团队模型之间进行引用的方法>>

在您的迁移文件中进行如下更改,这将创建与以前不同的high_school_team_id和club_team_id

class CreatePlayers < ActiveRecord::Migration[6.0]
  def change
    create_table :players do |t|
      t.string :first_name
      t.string :middle_name
      t.string :last_name
      t.decimal :height
      t.decimal :weight
      t.date :birthday
      t.references :high_school_team, index: true
      t.references :club_team, index: true
      t.decimal :gpa
      t.string :class_year
      t.string :intended_major
      t.string :email
      t.string :phone_number
      t.text :notes

      t.timestamps
    end
  end
end

在Player.rb中,您声明关系如下

belongs_to :high_school_team, foreign_key: "high_school_team_id", class_name: "Team"
belongs_to :club_team, foreign_key: "club_team_id", class_name: "Team"

在Team.rb内部,您声明关系如下

has_many :high_school_players, foreign_key: :high_school_team_id, class_name: "Player"
has_many :club_players, foreign_key: :club_team_id, class_name: "Player"

0
投票

您提到的文档讨论了需要在现有表中添加引用的情况。


0
投票

[如果要设置不能从表名(第一个参数)派生表的外键列,则只需传递foreign_key: { to_table: :teams}

© www.soinside.com 2019 - 2024. All rights reserved.