按 belongs_to 自定义搜索 foreign_key

Search by belongs_to custom foreign_key

我尝试通过 2 个团队搜索匹配项,我尝试了几种语法,但没有任何帮助...

模型匹配:

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

模范队:

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

我试过这样的事情:

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

错误:

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

选项 1.

在 Rails 控制台查询 puts Match.joins(:home, :away).to_sql 中检查。 您可能会得到如下结果:

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"

如果是这样,请使用类似

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

选项 2.

尝试像

这样的查询
Match.where(home: Team.where(name: 'Germany'), away: Team.where(name: 'China'))

您还可以 pre-find 团队 ID:

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)