ActiveRecord的有两个协会 [英] ActiveRecord has two association
问题描述
什么是实现有两个协会的ActiveRecord的最佳方法是什么?
我有一个团队和游戏模式。每个小组将have_many游戏 @ team.games
。博弈将有两支队伍 @ game.hosting_team
和 @ game.opposing_team
。
我开始了两个 belongs_to的/ HAS_ONE
的关联,但随后 @ team.games
只会返回他们的主场比赛
其他的选择,我能想到的是使用HABTM和使用验证,以确保只有记录。唯一缺少的是跟踪主队。好像我需要一个有许多通过关联,但我不是很确定...
感谢您的帮助。
这是两个has_many关联如何看一个例子。这里的问题是我必须调用 team.games
和 team.opponents
来得到他们的游戏的完整列表
类团队及LT;的ActiveRecord :: Base的
的has_many:游戏
的has_many:对手:将class_name => 团队#:foreign_key =>
结束
一流的游戏和LT;的ActiveRecord :: Base的
belongs_to的:团队:将class_name => 团队#:foreign_key => TEAM_ID
belongs_to的:对手:将class_name => 团队#:foreign_key => opponent_id
结束
我想这样的事情,但是这显然并不怎么belongs_to的工作。
类团队及LT;的ActiveRecord :: Base的
的has_many:游戏
结束
一流的游戏和LT;的ActiveRecord :: Base的
belongs_to的:hosting_team
belongs_to的:opposing_team
结束
我需要的API应该是这样的。
@ team.games#返回所有的游戏在家或外出
@ game.hosting_team#团队
@ game.opposing_team#团队
您可以或许仍与BT /豪关联建模它,并设置了游戏,对球队的存取方法,而不是作为一个协会:
类团队及LT;的ActiveRecord :: Base的
高清游戏
Game.find(:条件=>home_team_id = OR away_team_id =?,ID,ID])
结束
结束
What is the best way to achieve a has two association with activerecord?
I have a Team and Game models. Each Team will have_many games @team.games
. A Game will have two teams @game.hosting_team
and @game.opposing_team
.
I started out with two belongs_to/has_one
associations but then @team.games
would only return their home games.
The other option I can think of is using a HABTM and use a validator to ensure there are only records. The only thing missing is keeping track of the home team. It seems like I need a has many through association but I'm not exactly sure...
Thanks for your help.
This is an example of how the two has_many associations look. The problem here is I would have to call team.games
and team.opponents
to get a full list of their games
class Team < ActiveRecord::Base
has_many :games
has_many :opponents, :class_name => "Team"#, :foreign_key => ""
end
class Game < ActiveRecord::Base
belongs_to :team, :class_name => "Team" #, :foreign_key => "team_id"
belongs_to :opponent, :class_name => "Team" #, :foreign_key => "opponent_id"
end
I'd like something like this but this obviously isn't how belongs_to works.
class Team < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
belongs_to :hosting_team
belongs_to :opposing_team
end
My desired api would look like this.
@team.games # return all games home or away
@game.hosting_team # Team
@game.opposing_team # Team
You can probably still model it with the bt/ho associations, and set up games as an accessor method on the team instead of as an association:
class Team < ActiveRecord::Base
def games
Game.find(:conditions => ["home_team_id = ? OR away_team_id = ?", id, id])
end
end
这篇关于ActiveRecord的有两个协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!