因此,我有以下两种模型:
class City < ActiveRecord::Base
has_and_belongs_to_many :companies
end
class Company < ActiveRecord::Base
has_and_belongs_to_many :cities
end
联接表迁移为:
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
我正在尝试根据城市ID查找公司:
class CompaniesController < ApplicationController
def index
@companies = Company.includes(:cities).where('city.id' => params[:city_id]).references(:cities)
render :text => @companies.inspect
end
end
我得到的是:
PG :: UndefinedTable:错误:缺少表“ city”第1行的FROM子句条目:... cities“。” id“ =” cities_companies“。” city_id“在” city“。” id ... ^:SELECT “ company”。“ id” AS t0_r0,“ companies”。“名称” AS t0_r1,“ companies”。“ category_id” AS t0_r2,“ companies”。“ url” AS t0_r3,“ companies”。“ created_at” AS t0_r4, “公司”。“ updated_at” AS t0_r5,“公司”。“ image_file_name” AS t0_r6,“公司”。“ image_content_type” AS t0_r7,“公司”。“ image_file_size” AS t0_r8,“公司”。 “ cities”。“ id” AS t1_r0,“ cities”。“ name” AS t1_r1,“ cities”。“ state_id” AS t1_r2,“城市”。“ created_at” AS t1_r3,“城市”。“ updated_at” AS t1_r4从“ companies”左外联接“ cities_companies”在“ cities_companies”上。“ company_id” =“ companies “。” id“左外联接” cities“在” cities“上。” id“ =” cities_companies“。” city_id“在” city“。” id“ ='14'城市“。” id“ =”城市_公司“。” city_id“其中”城市“。” id“ ='14'城市“。” id“ =”城市_公司“。” city_id“其中”城市“。” id“ ='14'
我尝试了一些事情,例如将参数强制转换为int,但是我需要一些帮助来弄清楚这里发生了什么。
问题出在您的where
条款中。
你引用city.id
时,它应该是cities.id
作为表名是城市。
更好的书写方式是使用哈希语法
Company.includes(:cities).where(cities: { id: params[:city_id] }).references(:cities)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句