【问题标题】:Rails HABTM query only returning matching associationsRails HABTM 查询仅返回匹配的关联
【发布时间】:2020-10-10 12:30:29
【问题描述】:

我正在尝试为他们的关联创建一个记录过滤器。所以我有创意,他们有多种才能。我想要过滤具有特定才能的创意的 av 视图。但仍会在视图中显示每个广告素材的多个人才。

class Creative
  has_and_belongs_to_many :talents
end

创意 -> HABTM -> 人才

@creatives = Creative.includes(:talents, user: [:profile_image_attachment])
@creatives = @creatives.where(talents: { id: searched_talent_id })

问题是当显示每个creative 时,它只返回匹配的人才。

所以渲染:

<% @creatives.each do |creative| %>
  <% creative.talents.each do |talent| %>
    <%= talent.name %>
  <% end %>
<% end %>

只显示查询匹配的人才,而不是全部。 IE。该广告素材具有多种才能。

如果我更改代码以包含对 .all 的调用。

<% @creatives.each do |creative| %>
  <% creative.talents.all.each do |talent| %>
    <%= talent.name %>
  <% end %>
<% end %>

然后我确实得到了所有的人才,但数据库被每个创意的查询所击中。 我可以避免这种情况吗? IE。渴望加载所有创意人才,不受我搜索的限制!?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您可以通过使用子查询来解决这个问题:

    @creatives = Creative.includes(:talents, user: [:profile_image_attachment])
            .where(
              id: Creative.joins(:talents)
                          .where(talents: { id: searched_talent_id })
            )
    

    这将创建以下 SQL:

    SELECT 
      "creatives".* FROM "creatives" 
    WHERE 
      "creatives"."id" IN (
        SELECT "creatives"."id" 
        FROM "creatives" 
        INNER JOIN "creatives_talents" ON "creatives_talents"."creative_id" = "creatives"."id" 
        INNER JOIN "talents" ON "talents"."id" = "creatives_talents"."talent_id"       
        WHERE "talents"."id" = $1
      ) 
    LIMIT $2 
    

    这仅将 WHERE 子句应用于子查询,而不是 .includes 获取的行。

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多