Wil*_*les 4 ruby-on-rails foreign-keys has-many belongs-to
我正在尝试通过has_many,belongs_to关系将比赛归因于俱乐部。但是,在比赛中,我需要将俱乐部设置为home_team或away_team。为了解决这个问题,我使用了两个foreign_key。
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
Run Code Online (Sandbox Code Playgroud)
这样可以使用home_team_id和away_team_id在比赛中很好地设置俱乐部。
但是,我无法通过Club.matches访问所有俱乐部的比赛。
ERROR: column matches.club_id does not exist
Run Code Online (Sandbox Code Playgroud)
我该如何改变自己的关系,以便做到这一点?
我对Rails(3.2)中的Associations和(多个)外键的回答:如何在模型中描述它们并编写迁移只适合您!
至于你的代码,这是我的修改
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
Run Code Online (Sandbox Code Playgroud)
有什么问题吗?
| 归档时间: |
|
| 查看次数: |
2373 次 |
| 最近记录: |