Has_many通过/条件

时间:2014-07-29 15:45:51

标签: sql ruby-on-rails postgresql activerecord has-many-through

我在Rails 4中使用has_many通关系,看起来像这样:

has_many :collection_memberships, as: :collectable
has_many :collections, through: :collection_memberships
has_many :brands, -> { where(kind: 'brand') }, class_name: Collection,
         through: :collection_memberships, source: :collection

如果我有一个名为my_obj的对象并执行my_obj.brands,它会按预期工作:

SELECT "collections".* FROM "collections" INNER JOIN "collection_memberships"
 ON "collections"."id" = "collection_memberships"."collection_id" WHERE 
 "collections"."kind" = 'brand' AND "collection_memberships"."collectable_id"
 = $1 AND "collection_memberships"."collectable_type" = $2  ORDER BY
 collection_memberships.position ASC

但是,如果我尝试使用:includes做一些急切的加载:

p = Product.where(id: product_ids).includes(:brands)

发生这种情况:

Product Load  SELECT "products".* FROM "products"  WHERE "products"."id" IN (.....)

CollectionMembership Load   SELECT "collection_memberships".* FROM 
"collection_memberships"  WHERE "collections"."kind" = 'brand' AND 
"collection_memberships"."collectable_type" = 'Product' AND 
"collection_memberships"."collectable_id" IN (...)  ORDER BY 
collection_memberships.position ASC

[ERROR] PG::UndefinedTable: ERROR:  missing FROM-clause entry for
table "collections"
LINE 1: ...mberships".* FROM "collection_memberships"  WHERE "collectio...

ActiveRecord在查询中加入“集合”。“kind”=“品牌”,只是加载集合成员资格。它似乎应该在随后的查询中,或者该查询应该具有内部联接。有什么建议?我想把它作为一个协会。

其他相关模型:

class CollectionMembership < ActiveRecord::Base
  belongs_to :collection, touch: true
  belongs_to :collectable, polymorphic: true
end

class Collection < ActiveRecord::Base
  has_many :collection_memberships
  has_many :products, source_type: 'Product', through: :collection_memberships, source: :collectable
end

1 个答案:

答案 0 :(得分:1)

试试这个:

has_many :brands, -> { where(collections:{kind:'brand'}) },
  through: :collection_memberships, source: :collection