我对在 Rails 和 Active Record 上使用 ruby 完全陌生。 我似乎无法弄清楚为什么我不断收到此错误。我试图通过 destroy 方法删除足球队,但它不起作用。完整的错误内容如下:
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column matches.team_id does not exist LINE 1: SELECT "matches".* FROM "matches" WHERE "matches"."team_id" ... ^ ):
每场比赛有两支球队,一个球队可以有很多比赛和球员,以下是班级的样子:
class Team < ApplicationRecord
has_many :players , dependent: :destroy
has_many :matches, foreign_key: "team_id", dependent: :destroy
end
class Match < ApplicationRecord
belongs_to :teamA, foreign_key: "team_id", class_name: "Team"
belongs_to :teamB, foreign_key: "team_id", class_name: "Team"
end
class CreateMatches < ActiveRecord::Migration[7.0]
def change
create_table :matches do |t|
t.references :teamA, foreign_key: { to_table: :teams }
t.references :teamB, foreign_key: { to_table: :teams }
t.index: :teams, :teams_id, unique: true
t.boolean :state
t.string :result
t.timestamps
end
end
end
问题出在哪里? 我使用外键来尝试使这些关联发挥作用,因为我看到了一些推荐它的帖子,但它对我不起作用。
正如评论中指出的,您的团队中没有
team_id
列,但有 teamA_id
和 teamB_id
,如果您单独指定它们,您将能够调用 #destroy
class Team < ApplicationRecord
has_many :players , dependent: :destroy
has_many :matches_as_A_team, foreign_key: "teamA_id", class_name: 'Match', dependent: :destroy
has_many :matches_as_B_team, foreign_key: "teamB_id", class_name: 'Match'. dependent: :destroy
end
但坦率地说,这不是一个伟大的设计。我建议采用不同的方法...也许是一个比赛表、一个球队表和一个既属于比赛又属于球队的连接表“matches_teams”。您可以将有关球队在比赛中的角色的信息放入连接表本身(例如,布尔值“主场”,对于主队来说为真,对于客队为假。