【问题标题】:Has Many Through w/ Conditions有很多通过 w/ 条件
【发布时间】:2014-09-21 01:43:22
【问题描述】:

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

【问题讨论】:

  • 能否包含来自CollectionMembershipCollection 的相关关联?

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


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    相关资源
    最近更新 更多