定义对另一个表中同一列的两个引用
我的项目中有一个团队表.我已经使用以下命令进行了应该创建表 Match 的迁移:
There's a Team table in my project. I've made a migration that is supposed to create table Match using the command below:
rails generate model Match Team:references Team:re
ferences score1:integer score2:integer date:datetime length:integer place:string
我希望我的 Matches 表包含 2 个引用 Teams 上相同列 (id) 的外键(team1、team2) 表.我很确定我做错了,因为在 schema.rb 中有:
I want my Matches table to contain 2 foreign keys (team1, team2) referencing same column (id) on Teams table. I'm pretty sure I did this wrong, because in schema.rb there's:
create_table "matchs", force: true do |t|
t.integer "Team_id"
t.integer "score1"
t.integer "score2"
t.datetime "date"
t.integer "length"
t.string "place"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "matchs", ["Team_id"], name: "index_matchs_on_Team_id"
而且我看不到第二个 Team_id.做我需要的正确方法是什么?
and I can't see 2nd Team_id. What is the proper way to do what I need?
一个数据库表不能有两列同名.这是您要使其工作所需要的.(我将使用 home_team
和 away_team
来帮助区分它们,但显然你可以使用 team1
和 team2
>.)
A database table cannot have two columns with the same name. This is what you'll need in order to get this to work. (I'm going to use home_team
and away_team
to help distinguish them, but obviously you could use team1
and team2
.)
rails g migration AddTeamsToMatch home_team_id:integer away_team_id:integer
这将生成如下所示的迁移:
This will generate a migration that looks like this:
class AddTeamsToMatch < ActiveRecord::Migration
def change
add_column :matches, :home_team_id, :integer
add_column :matches, :away_team_id, :integer
end
end
然后在您的 Team
模型中,您可以拥有以下内容:
Then in your Team
model, you can have the following:
class Team < ActiveRecord::Base
has_many :home_matches, class_name: "Match", foreign_key: "home_team_id"
has_many :away_matches, class_name: "Match", foreign_key: "away_team_id"
# Get all matches
def matches
self.home_matches + self.away_matches
end
end
在您的 Match
模型中,您可以:
In your Match
model, you can have:
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: "Team"
belongs_to :away_team, class_name: "Team"
# List both teams as array
def teams
[self.home_team, self.away_team]
end
end
希望这会有所帮助.