2017-03-15 2 views
1

私はORの条件をhas_manyのためにシミュレートしたいので、アクティブなレコードの関連付けを失うことはありません。私はこれが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_idまたはhome_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 –

関連する問題