Reputation: 399
So, I have these two models:
class City < ActiveRecord::Base
has_and_belongs_to_many :companies
end
class Company < ActiveRecord::Base
has_and_belongs_to_many :cities
end
And the join table migration is:
class CreateJoinCityCompany < ActiveRecord::Migration
def up
create_table :cities_companies do |t|
t.integer :city_id
t.integer :company_id
end
end
def down
drop_table :cities_companies
end
end
I'm trying to find companies based on a city ID:
class CompaniesController < ApplicationController
def index
@companies = Company.includes(:cities).where('city.id' => params[:city_id]).references(:cities)
render :text => @companies.inspect
end
end
And What I get is:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "city" LINE 1: ...cities"."id" = "cities_companies"."city_id" WHERE "city"."id... ^ : SELECT "companies"."id" AS t0_r0, "companies"."name" AS t0_r1, "companies"."category_id" AS t0_r2, "companies"."url" AS t0_r3, "companies"."created_at" AS t0_r4, "companies"."updated_at" AS t0_r5, "companies"."image_file_name" AS t0_r6, "companies"."image_content_type" AS t0_r7, "companies"."image_file_size" AS t0_r8, "companies"."image_updated_at" AS t0_r9, "cities"."id" AS t1_r0, "cities"."name" AS t1_r1, "cities"."state_id" AS t1_r2, "cities"."created_at" AS t1_r3, "cities"."updated_at" AS t1_r4 FROM "companies" LEFT OUTER JOIN "cities_companies" ON "cities_companies"."company_id" = "companies"."id" LEFT OUTER JOIN "cities" ON "cities"."id" = "cities_companies"."city_id" WHERE "city"."id" = '14'
I tried a few things, like casting the parameter to int, but I need some help to figure out what's going on here.
Upvotes: 0
Views: 210
Reputation: 45002
The problem is in your where
clause.
You are referencing city.id
when it should be cities.id
as the table name is city.
An even nicer way of writing it would be to use the hash syntax
Company.includes(:cities).where(cities: { id: params[:city_id] }).references(:cities)
Upvotes: 1