【问题标题】:ActiveRecord has two associationActiveRecord 有两个关联
【发布时间】:2010-11-28 19:09:05
【问题描述】:

实现与 activerecord 的两个关联的最佳方法是什么?

我有一个团队和游戏模型。每个团队将有_many 游戏@team.games。一场比赛将有两支队伍@game.hosting_team@game.opposing_team

我一开始有两个 belongs_to/has_one 协会,但后来 @team.games 只会返回他们的主场比赛。

我能想到的另一个选择是使用 HABTM 并使用验证器来确保只有记录。唯一缺少的是跟踪主队。似乎我需要一个有很多的关联,但我不确定......

感谢您的帮助。

这是两个 has_many 关联的外观示例。这里的问题是我必须致电team.gamesteam.opponents 才能获得他们游戏的完整列表

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

我想要这样的东西,但这显然不是 belongs_to 的工作方式。

class Team < ActiveRecord::Base
  has_many :games
end

class Game < ActiveRecord::Base
  belongs_to :hosting_team
  belongs_to :opposing_team
end

我想要的 api 应该是这样的。

@team.games # return all games home or away
@game.hosting_team # Team
@game.opposing_team # Team

【问题讨论】:

  • 你能校准模型的关系并发布你的 db/schema.rb 吗?
  • 谢谢。我编辑了问题。

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您可能仍然可以使用 bt/ho 关联对其进行建模,并将游戏设置为团队中的访问器方法而不是关联:

class Team < ActiveRecord::Base
  def games
    Game.find(:conditions => ["home_team_id = ? OR away_team_id = ?", id, id])
  end
end

【讨论】:

  • 是的,好主意。我的团队模型将 have_many :home_games 和 have_many away_games。然后你的游戏方法会同时选择它们。谢谢,这可能是答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多