我在 Rails 4 中使用 has_many through 关系,它看起来像这样:
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 在加载集合成员资格时将 "collections"."kind"= 'brand' 放入查询中。看起来它应该在随后的查询中,或者该查询应该有一个内部连接。有什么建议么?我想将其保留为一个关联。
其他相关模型:
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
最佳答案
试试这个:
has_many :brands, -> { where(collections:{kind:'brand'}) },
through: :collection_memberships, source: :collection
关于sql - 有很多条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019489/