I want to simulate OR
conditions for has_many
association so I do not lose active record association. I understand this can be achieved using scope
or instance method but in that case, I will lose association.
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
You can do something like this:
Here it will first remove the original scope :team_id
and use away_team_id
or home_team_id
instead.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With