table" stores"有一个条目,但不能从查询的这一部分引用它

时间:2015-05-04 05:48:29

标签: ruby-on-rails postgresql activerecord

我想从我的商店中选择最近的4笔交易,并且有has_and_belongs_to_many关系,我收到此错误:

  

表" store"有一个条目,但不能引用它   这部分查询

class Deal < ActiveRecord::Base
   has_and_belongs_to_many :stores
end

class Store < ActiveRecord::Base
   has_and_belongs_to_many :deals
end

我的查询

SELECT * FROM (SELECT stores.id AS store_id,       deals.*,
      dense_rank() OVER (
        PARTITION BY deals.stores.id
        ORDER BY deals.created_at DESC
      ) AS deal_rank
 FROM "deals" 
 INNER JOIN "listings" 
 ON "listings"."deal_id" = "deals"."id" 
 INNER JOIN "images" 
 ON "images"."id" = "deals"."image_id" 
 INNER JOIN "deals_stores" 
 ON "deals_stores"."deal_id" = "deals"."id" 
 INNER JOIN "stores" 
 ON "stores"."id" = "deals_stores"."store_id"  
 ORDER BY deals.created_at desc) 
 AS ranked_deals  
 WHERE (deal_rank <= 4)

1 个答案:

答案 0 :(得分:0)

在定义habtm关系时,您应该更喜欢复数版本。

您需要更改

has_and_belongs_to_many :store

has_and_belongs_to_many :stores