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

标签 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。谁能告诉我我做错了什么?谢谢,

最佳答案

如果 Game has_one :team 那么 Rails 假设您的 teams 表有一个 game_id 列。不过,您想要的是 games 表有一个 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

关于ruby - Rails 关联 - 同一个类的多个 has_one 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9037340/

相关文章:

ruby - 乘号:* do?是什么意思

mysql - Ruby 模型将 Controller 值存储在 MYSQL 中并添加字符

ruby-on-rails - 查找没有任何关联模型的所有记录

ruby - 是 &method( :method_name) idiom bad for performance in Ruby?

ruby-on-rails - Rails (4.2.0) 服务器对浏览器请求无响应

ruby-on-rails - 无方法错误 : undefined method `get' when running rspec and making get/visit calls

ruby - 如何让 has_secure_password 在生产中工作?

ruby win32ole MS Access : How to find all the records updated since last export?

ruby-on-rails - Rails Where 子句中的字符串到日期的转换

ruby-on-rails - 即时构建 rails Form 和 Form_Fields