我试图通过 has_many、belongs_to 关系将比赛归因于俱乐部。然而,在比赛中,我需要将俱乐部设置为 home_team 或away_team。为了解决这个问题,我使用了两个外键。
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
我如何改变我的关系才能做到这一点?
最佳答案
至于你的代码,这是我的修改
class Club < ActiveRecord::Base
has_many :matches, ->(club) { unscope(where: :club_id).where("home_team_id = ? OR away_team_id = ?", club.id, club.id) }, class_name: 'Match'
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
还有什么问题吗?
关于ruby-on-rails - Has_many、belongs_to 具有多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514293/