Search code examples
ruby-on-railspostgresqlactiverecordhas-manybelongs-to

Search by belongs_to custom foreign_key


I try to search for a match via the 2 teams, I tried several syntax, but nothing helps ...

Model Match:

class Match < ApplicationRecord
  belongs_to :home, class_name: 'Team', foreign_key: :home_id
  belongs_to :away, class_name: 'Team', foreign_key: :away_id
end

Model Team:

class Team < ApplicationRecord
  has_many :home_matches, class_name: 'Match', foreign_key: :home_id
  has_many :away_matches, class_name: 'Match', foreign_key: :away_id

  # Fields: name
end

I tried something like this:

 Match.includes(:home, :away).where(homes: { name: 'Germany' }, aways: {name: 'China'})

Error:

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "homes")


Solution

  • Option 1.

    Inspect in Rails Console query puts Match.joins(:home, :away).to_sql. You could get result like:

    SELECT "matches".* FROM "matches" INNER JOIN "teams" ON "teams"."id" = "matches"."home_id" INNER JOIN "teams" "away_matches" ON "away_matches"."id" = "matches"."away_id"
    

    If so, use query like

    Match.joins(:home, :away).where(teams: { name: 'Germany' }, away_matches: {name: 'China'})
    

    Option 2.

    Try query like

    Match.where(home: Team.where(name: 'Germany'), away: Team.where(name: 'China'))
    

    You can also pre-find ids of Teams:

    home_id = Team.find_by(name: 'Germany').id
    away_id = Team.find_by(name: 'China').id
    Match.where(home_id: home_id, away_id: away_id)