按belongs_to自定义foreign_key搜索

时间:2019-05-30 09:52:53

标签: ruby-on-rails postgresql activerecord has-many belongs-to

我尝试通过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:错误:缺少   表“ homes”的FROM子句条目)

1 个答案:

答案 0 :(得分:2)

选项1。

在Rails Console查询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'))

您还可以预查找团队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)