rails:HABTM和ActiveRecord出错(PG :: UndefinedTable:ERROR:缺少FROM ...)

时间:2014-12-17 23:49:28

标签: ruby-on-rails activerecord psql

所以,我有这两个模型:

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:错误:表&#34; city&#34;缺少FROM子句条目   第1行:......城市&#34;。&#34; id&#34; =&#34; cities_companies&#34;。&#34; city_id&#34;哪里   &#34; city&#34;。&#34; id ... ^:SELECT&#34;公司&#34;。&#34; id&#34; AS t0_r0,&#34;公司&#34;。&#34;名称&#34;   AS t0_r1,&#34;公司&#34;。&#34; category_id&#34; AS t0_r2,&#34;公司&#34;。&#34; url&#34;如   t0_r3,&#34;公司&#34;。&#34; created_at&#34; AS t0_r4,&#34;公司&#34;。&#34; updated_at&#34;如   t0_r5,&#34;公司&#34;。&#34; image_file_name&#34; AS t0_r6,   #&34;公司&#34;&#34; image_content_type&#34; AS t0_r7,   #&34;公司&#34;&#34; IMAGE_FILE_SIZE&#34; AS t0_r8,&#34;公司&#34;。&#34; image_updated_at&#34;   AS t0_r9,&#34; cities&#34;。&#34; id&#34; AS t1_r0,&#34; cities&#34;。&#34; name&#34; AS t1_r1,   &#34;城市&#34;&#34; STATE_ID&#34; AS t1_r2,&#34; cities&#34;。&#34; created_at&#34; AS t1_r3,   #&34;城市&#34;&#34;的updated_at&#34; AS t1_r4 FROM&#34;公司&#34; LEFT OUTER JOIN   &#34; cities_companies&#34; ON&#34; cities_companies&#34;。&#34; company_id&#34; =   &#34;公司&#34;&#34;编号&#34; LEFT OUTER JOIN&#34; cities&#34; ON&#34;城市&#34;。&#34; id&#34; =   #&34; cities_companies&#34;&#34; city_id&#34;在哪里&#34;城市&#34;。&#34; id&#34; =&#39; 14&#39;

我尝试了一些方法,比如将参数转换为int,但我需要一些帮助来弄清楚这里发生了什么。

1 个答案:

答案 0 :(得分:1)

问题出在你的where条款中。

您引用city.id时应该是cities.id,因为表名是城市。

更好的编写方法是使用哈希语法

Company.includes(:cities).where(cities: { id: params[:city_id] }).references(:cities)