Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate `OR` conditions for `has_many` association in Rails 5?

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
like image 496
Nilay Anand Avatar asked Mar 09 '23 14:03

Nilay Anand


1 Answers

You can do something like this:

Here it will first remove the original scope :team_id and use away_team_idor 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
like image 192
Lasse Sviland Avatar answered Apr 30 '23 01:04

Lasse Sviland