2017-03-15 73 views
1

我想爲has_many關聯模擬OR條件,所以我不會失去活動記錄關聯。我知道這可以通過使用scope或實例方法來實現,但在這種情況下,我將失去聯繫。如何在Rails 5中模擬`has_many`關聯的`OR`條件?

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 

回答

1

你可以做這樣的事情:

這會先刪除原來的範圍:team_id,並使用away_team_idhome_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 
+0

它的作品完美。謝謝Lasse Sviland –