Ruby on rails PG::UndefinedColumn:错误:column services.zip_代码不存在

Ruby on rails PG::UndefinedColumn:错误:column services.zip_代码不存在,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,我有两种型号(Service和Town)与:有很多:通过关系。我希望能够找到一个城镇的每一项服务,以及一项服务的每一个城镇 同样在前面,我永远也看不到我的城镇ID,所以我只能用城镇的邮政编码链接服务和城镇 这是我所有的迁移 create_table :services, type: :uuid do |t| t.string :name, null: false t.string :action, null: false t.string :kind, null:

我有两种型号(
Service
Town
)与
:有很多:通过
关系。我希望能够找到一个城镇的每一项服务,以及一项服务的每一个城镇

同样在前面,我永远也看不到我的城镇ID,所以我只能用城镇的邮政编码链接服务和城镇

这是我所有的迁移

create_table :services, type: :uuid do |t|
  t.string :name,     null: false
  t.string :action,   null: false
  t.string :kind,     null: false
end

create_table :towns do |t|
  t.string :name,     null: false
  t.stirng :zip_code, null: false
  t.string :country,  null: false
end

create_table :services_towns do |t|
  t.belongs_to :service
  t.belongs_to :town

  t.string :zip_code, null: false

  t.index :zip_code
end
这是我的模型


class Town < ApplicatonRecord
  has_many :services_towns, primary_key: :zip_code, foreign_key: :zip_code
  has_many :services,       through: :services_communes
end

class Service < ApplicationRecord
  has_many :services_towns
  has_many :towns, through: :services_communes
end

class ServicesTown < ApplicationRecord
  belongs_to :service
  belongs_to :town, primary_key: :zip_code, foreign_key: :zip_code
end
有了这个请求,我希望能从阵列中经过的每个城镇获得所有服务


我猜问题是因为我的
主键
外键
造成的,但我不知道该怎么做才能更好

您需要修复您的查询,试试这个

Service.joins(:towns).where(towns: { zip_code: towns_array })

Service.joins(:towns).where("towns.zip_code IN (?)", towns_array)    

希望有帮助

towns\u数组中有什么?
?它将是一个邮政编码数组,如[“27310”、“12300”、“48700”]
Service.joins(:towns).where("towns.zip_code IN (?)", towns_array)