首页 > 解决方案 > Rails 深度嵌套连接

问题描述

我有以下型号

class Doctor < ApplicationRecord
  has_many :practices
  has_many :facilities, through: :practices
  has_one :address, as: :addressable
  ...
end

class Facility < ApplicationRecord
  has_many :practices
  has_many :doctors, through: :practices
  has_one  :address, as: :addressable
end

class Practice < ApplicationRecord
  belongs_to :doctor
  belongs_to :facility
end

class Address < ApplicationRecord
  belongs_to :addressable, polymorphic: true
  belongs_to :city
  belongs_to :state
  belongs_to :country
end

医生可以在一个cidy的不止一次设施中练习。我想使用连接(除非有更有效的方法)来查找在一个城市执业的所有医生的列表。我写了一个嵌套连接如下

Doctor.joins(facilities: [address: :city]) # Works

我无法解决编写用于指定城市名称的 where 子句的问题。

Doctor.joins(facilities: [address: [:city]]).where({facilities: {address: {city: {name: "Sydney"}}})

我收到一个错误,上面写着

Mysql2::Error: Unknown column 'address.name' in 'where clause'

请帮忙!

标签: ruby-on-railsactiverecord

解决方案


你已经加载cityaddress,你在内存中有命名空间:

Doctor.joins(facilities: { address: :city }).where(cities: { name: city_name })

推荐阅读