Nil*_*and 4 ruby-on-rails rails-activerecord ruby-on-rails-5
我想模拟关联OR条件,has_many这样我就不会丢失活动记录关联。我知道这可以使用scope或实例方法来实现,但在这种情况下,我将失去关联。
class Game < ActiveRecord::Base
belongs_to :home_team, :class_name => "Team"
belongs_to :away_team, :class_name => "Team"
has_many :sponsors
end
class Sponsor < ActiveReord::Base
belongs_to :game
end
class Team < ActiveRecord::Base
has_many :away_games, :class_name => "Game", :foreign_key => "away_team_id"
has_many :home_games, :class_name => "Game", :foreign_key => "home_team_id"
# what I want here like:
# has_many :games, :foreign_key => [:home_team_id, :away_team_id]
# so I could achieve without losing association helper:
# has_many :sponsors through: :games
end
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
在这里它将首先删除原始范围:team_id并使用away_team_idorhome_team_id代替。
has_many :games, ->(team){ unscope(where: :team_id)
.where('away_team_id = :team_id OR home_team_id = :team_id', team_id: team.id) }
has_many :sponsors, through: :games
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |