我的问题的一个例子是体育游戏。一场体育比赛有两支球队,一支主队和一支客队。我的事件记录模型如下:
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/