连接表的条件 - Rails

时间:2012-11-20 21:25:21

标签: ruby-on-rails postgresql

我的模特:

class Review < ActiveRecord::Base 
  belongs_to :business

class Business < ActiveRecord::Base
  has_many :reviews
  has_and_belongs_to_many :categories

我想获得特定类别下的商家评论:

Review.joins(:business => :categories).where(:business => {:categories => [1,2,3,4]})

结果查询:

SELECT "reviews".* FROM "reviews" INNER JOIN 
"businesses" ON "businesses"."id" = "reviews"."business_id" INNER JOIN 
"businesses_categories" ON "businesses_categories"."business_id" = "businesses"."id" 
INNER JOIN "categories" ON "categories"."id" = "businesses_categories"."category_id" 
WHERE "business"."categories" IN (1, 2, 3, 4)

但是,我收到以下错误:

ActiveRecord::StatementInvalid: PG::Error: ERROR:  missing FROM-clause entry 
for table "business"
LINE 1: ...id" = "businesses_categories"."category_id" WHERE "business"...

1 个答案:

答案 0 :(得分:3)

使用此:

Review.joins(:business => :categories).where( :categories => { :id => [1,2,3,4] } )