【发布时间】:2014-05-07 09:46:11
【问题描述】:
我试图通过 has_many,belongs_to 关系将比赛归因于俱乐部。但是,在比赛中,我需要将俱乐部设置为 home_team 或 away_team。为了解决这个问题,我使用了两个foreign_keys。
class Club < ActiveRecord::Base
has_many :matches
end
class Match < ActiveRecord::Base
belongs_to :home_team, class_name: 'Club', foreign_key: 'home_team_id'
belongs_to :away_team, class_name: 'Club', foreign_key: 'away_team_id'
end
这可以使用 home_team_id 和 away_team_id 很好地设置俱乐部。
但是,我无法通过 Club.matches 访问俱乐部的所有比赛。
ERROR: column matches.club_id does not exist
我怎样才能改变我的关系,这样我才能做到这一点?
【问题讨论】:
-
Users和Messages.from_id和Messages.to_id也有这个问题。我正在尝试has_many :messages, ->(u) {where "from_id = ? or to_id = ?", u.id, u.id}, foreign_key: nil,但没有成功。
标签: ruby-on-rails foreign-keys has-many belongs-to