Ruby on rails Rails HABTM查询仅返回匹配的关联
我正在尝试为他们的关联创建一个记录过滤器。所以我有创意,他们有多种才能。我想有一个av视图,过滤具有特定天赋的创意。但仍在视图中显示出各自创造的多重才能Ruby on rails Rails HABTM查询仅返回匹配的关联,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在尝试为他们的关联创建一个记录过滤器。所以我有创意,他们有多种才能。我想有一个av视图,过滤具有特定天赋的创意。但仍在视图中显示出各自创造的多重才能 class Creative has_and_belongs_to_many :talents end 创意->HABTM->人才 @creatives = Creative.includes(:talents, user: [:profile_image_attachment]) @creatives = @creatives.wher
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 })
问题是,当显示每个创意时,它只返回匹配的人才
因此:
<% @creatives.each do |creative| %>
<% creative.talents.each do |talent| %>
<%= talent.name %>
<% end %>
<% end %>
然后我确实得到了所有的人才,但数据库中的每一个创意都有查询。
我能避免这个吗?也就是说,渴望将所有的创意人才都投入其中,而不受我所搜索的人才的限制 您可以通过使用子查询来解决此问题:
@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
您可以使用子查询解决此问题:
@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
获取的行