Rails嵌套嵌套

时间:2019-09-20 10:35:35

标签: ruby-on-rails activerecord

我有以下型号

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

医生可以在一个科学城中多次练习。我想使用联接(除非有更有效的方法)来查找在城市中执业的所有医生的名单。我在下面写了一个嵌套联接

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'

请帮助!

1 个答案:

答案 0 :(得分:3)

您已通过city加载了address,您的内存中有名称空间:

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