I have the following setup:
我有以下设置:
One matchdays
table with a column called home_team_id
and one called visitor_team_id
and a team
table.
一个matchdays表,其中一列名为home_team_id,一个名为visitor_team_id,另一个名为team table。
My Match model looks like this:
我的匹配模型如下所示:
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: "Team", foreign_key: :home_team_id
belongs_to :visitor_team, class_name: "Team", foreign_key: :visitor_team_id
belongs_to :matchday
validates :home_team, presence: true
validates :visitor_team, presence: true
end
And the Team model like that:
团队模型是这样的:
class Team < ActiveRecord::Base
has_many :matches
has_many :player
end
Now it's getting tricky (at least for me). I'd like to be able to call team.matches
and get all of the matches for the team. Since every team has home games and also games on the road.
现在它变得棘手(至少对我而言)。我希望能够召集team.matches并获得团队的所有比赛。由于每个团队都有家庭游戏和游戏。
Currently I'm getting a ActiveRecord::StatementInvalid
Error because it's looking for the team_id
column in the matches table.
目前我收到一个ActiveRecord :: StatementInvalid错误,因为它正在匹配表中查找team_id列。
1 个解决方案
#1
0
So if I understand correctly, what you need is just a method that returns all games where the current team is playing. This should do the trick:
因此,如果我理解正确,您需要的只是一种返回当前团队正在玩的所有游戏的方法。这应该是诀窍:
class Team < ActiveRecord::Base
has_many :player
def matches
Team.where(home_team_id => self.id, foreign_key => self.id)
# This line will also work if you want to try it out.
# Team.where("home_team_id = ?", self.id).where("foreign_key = ?", self.id)
end
end
Happy coding!
快乐的编码!
#1
0
So if I understand correctly, what you need is just a method that returns all games where the current team is playing. This should do the trick:
因此,如果我理解正确,您需要的只是一种返回当前团队正在玩的所有游戏的方法。这应该是诀窍:
class Team < ActiveRecord::Base
has_many :player
def matches
Team.where(home_team_id => self.id, foreign_key => self.id)
# This line will also work if you want to try it out.
# Team.where("home_team_id = ?", self.id).where("foreign_key = ?", self.id)
end
end
Happy coding!
快乐的编码!