sql - 有很多条件

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

我在 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/

相关文章:

mysql - 关系数据库设计场景

SQL Server 子查询返回了 1 个以上的值。当尝试从另一个选择插入时子查询跟随时,这是不允许的

javascript - 如何在辅助 Rails 中从 collection_select 向路线发送 POST

ruby-on-rails - 是否可以在 Rails 迁移中使用自定义列类型?

postgresql - 错误 : function unnest(integer[]) does not exist in postgresql

SQL查询仅在存在重复项时按列过滤

java - HQL如何连接三张表

javascript - select2 在分页时与 ajax/jquery 中断

mysql - MySQL GROUP BY 的 PostgreSQL 等价物

c# - Dapper 和 Npgsql 通过使用带有 IN 子句和 List<int> 的 EXPLAIN 抛出异常