rails 迁移 2 支球队之间的比赛
rails migration for matches between 2 teams
我目前是在 rails 上使用 ruby 的初学者,试图确定我的模型 Matches
、Teams
.[=19 之间的关系=]
我希望我的匹配项引用 Teams
table 两次,一次是 homeTeam
,另一次是 awayTeam
。我想我最大的问题是,我是否在我的模型中错误地声明了关系?
目前我什至不能通过比赛叫出球队的名字。
我希望能够调用 Team.matches 来列出一支球队的所有比赛,无论是主场还是客场,并最终能够为特定球队调用主场或客场比赛。
我还希望能够调用 Match.teams/Match.homeTeam/Match.awayTeam 来列出特定比赛的球队。
这是我目前的情况:
匹配迁移
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.references :homeTeam
t.references :awayTeam
end
end
end
匹配模型
class Match < ActiveRecord::Base
has_one :homeTeam, :class_name => 'Team'
has_one :awayTeam, :class_name => 'Team'
end
团队模式
class Team < ActiveRecord::Base
has_and_belongs_to_many :matches
end
提前致谢!
你可以这样做:
class Match < ActiveRecord::Base
belongs_to :hometeam, :class_name => 'Team'
belongs_to :awayteam, :class_name => 'Team'
#if you want to select all teams of a match, you can create a method
def teams
Team.find(self.hometeam_id, self.awayteam_id)
end
end
class Team < ActiveRecord::Base
has_many :home, class_name: 'Match', foreign_key: 'hometeam_id'
has_many :away, class_name: 'Match', foreign_key: 'awayteam_id'
end
我目前是在 rails 上使用 ruby 的初学者,试图确定我的模型 Matches
、Teams
.[=19 之间的关系=]
我希望我的匹配项引用 Teams
table 两次,一次是 homeTeam
,另一次是 awayTeam
。我想我最大的问题是,我是否在我的模型中错误地声明了关系?
目前我什至不能通过比赛叫出球队的名字。
我希望能够调用 Team.matches 来列出一支球队的所有比赛,无论是主场还是客场,并最终能够为特定球队调用主场或客场比赛。
我还希望能够调用 Match.teams/Match.homeTeam/Match.awayTeam 来列出特定比赛的球队。
这是我目前的情况:
匹配迁移
class CreateMatches < ActiveRecord::Migration
def change
create_table :matches do |t|
t.references :homeTeam
t.references :awayTeam
end
end
end
匹配模型
class Match < ActiveRecord::Base
has_one :homeTeam, :class_name => 'Team'
has_one :awayTeam, :class_name => 'Team'
end
团队模式
class Team < ActiveRecord::Base
has_and_belongs_to_many :matches
end
提前致谢!
你可以这样做:
class Match < ActiveRecord::Base
belongs_to :hometeam, :class_name => 'Team'
belongs_to :awayteam, :class_name => 'Team'
#if you want to select all teams of a match, you can create a method
def teams
Team.find(self.hometeam_id, self.awayteam_id)
end
end
class Team < ActiveRecord::Base
has_many :home, class_name: 'Match', foreign_key: 'hometeam_id'
has_many :away, class_name: 'Match', foreign_key: 'awayteam_id'
end