Rails关联 - 与同一个类的多个has_one关系

时间:2012-01-27 17:17:19

标签: ruby ruby-on-rails-3 activerecord

我的问题的一个例子是体育比赛。体育游戏有两个团队,一个主队和一个客队。我的活跃记录模型如下:

class Team < ActiveRecord::Base

  belongs_to :game

end

class Game < ActiveRecord::Base

  has_one :home_team, :class_name => "Team"
  has_one :away_team, :class_name => "Team"

end

我希望能够通过游戏访问团队,例如:Game.find(1).home_team

但我得到了一个酉恒定错误:Game :: team。谁能告诉我我做错了什么?谢谢,

4 个答案:

答案 0 :(得分:7)

如果Game has_one :team,那么Rails会假设您的球队表有一个game_id列。你想要的是游戏表中有一个team_id列,在这种情况下你可以使用Game belongs_to :team。作为英语,在这种情况下听起来倒是倒是,但作为Ruby,它是正确的。

我做了一点简化。你想要的东西是:

class Team < ActiveRecord::Base
  has_many :home_games, :class_name => "Game", :foreign_key => 'home_team_id'
  has_many :away_games, :class_name => "Game", :foreign_key => 'away_team_id'
end

class Game < ActiveRecord::Base
  belongs_to :home_team, :class_name => "Team"
  belongs_to :away_team, :class_name => "Team"
end

答案 1 :(得分:1)

我刚刚测试了你的代码,它应该可以运行。

我怀疑你的文件名错了。确保app / models /中的文件名是:

  • game.rb
  • team.rb

而不是:

  • games.rb

  • teams.rb

答案 2 :(得分:1)

我认为这可能是您架构的错误。

游戏无法区分这个架构的两个团队。

所以,请像那样运行

rails g migration add_stadium_to_game stadium:integer
rails g migration add_home_to_team home:integer
rake db:migrate

并且,像那样编辑“game.rb”

class Game < ActiveRecord::Base

  has_many :teams

  def home_team
    teams.select { |team| team.home == self.stadium }.first
  end

  def away_team
    teams.select { |team| team.home != self.stadium }.first
  end

end

这是一个例子,所以有很多方法可以实现你的目的。

答案 3 :(得分:0)

听起来像命名空间问题。尝试为团队明确声明类(带命名空间)。例如:

has_one :home_team, :class_name => "::Team"

http://guides.rubyonrails.org/association_basics.html#the-has_one-association