【问题标题】:Search by belongs_to custom foreign_key按belongs_to 自定义foreign_key 搜索
【发布时间】:2019-05-30 09:52:53
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    选项 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'))
    

    您还可以预先查找 Teams 的 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)
    

    【讨论】:

    • 第一个选项Match.joins(:home, :away).where(teams: { name: 'Germany' }, away_matches: {name: 'China'}) dosent 工作,第二个选项是
    • @BorisBRESCIANI 选项 1 查询取决于 puts Match.joins(:home, :away).to_sql 确切显示的内容(可能取决于 Rails 版本)。
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多