简体   繁体   中英

PG::UndefinedColumn: ERROR: column services.zip_code does not exist

I have 2 models ( Service and Town ) with a :has_many :through relationship. I want to be able to find every services of a town and every towns of a service.

Also in front I should never be able to see my Town ID so I can link service and town only with the zip_code of a town.

Here is all my migrations

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

here are my models


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.towns and @town.services are working well in my rails console but if I try a more complex search like Service.where(towns: [towns_array]) I got the following error

PG::UndefinedColumn: ERROR:  column services.zip_code does not exist

With this request I would like to have every Services from every Towns I have passed in the array.

I guess the problem are because of my primary_key or foreign_key but I don't know what to do better

You need to fix your query, try this

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

or

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

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM