Why doesn't my query deliver singular results?

Hello,

I have following query with group by and having plus count. It should return only those entries specified in the group by clause as they have count.

@articles = Article.joins(:taggings).where(taggings: { tag_id: @article_tags_ids, taggable_type: "Article"}).group('articles.id').having("count(taggings.tag_id) = ?", @article_tags_count)

The models behind this are from here https://cobwwweb.com/rails-has-many-through-polymorphic-association

It shall only and exactly return articles with the tags the user searches for. It shall decidedly not return those articles that have the tags the user searched for plus others.

Although the groub().having(“count…”) defining the number of permissable tag-entries it does return latter article-entries with tags-searched-for-plus-others.

Yours sincerely

von Spotz

Some more information would be helpful. What’s in @article_tags_ids and @article_tags_count? Where do they come from? Exactly what results are you (1) expecting to get, (2) expecting not to get, and (3) actually getting?

Hello pjscopeland,

@article_tags_ids are the ids of the tags searched for
@article_tags_count is their count for the having count-clause.

The generated SQL query is

SELECT
  `articles`.* 
FROM
  `articles` 
INNER JOIN `taggings` 
  ON `taggings`.`taggable_id` = `articles`.`id` 
  AND `taggings`.`taggable_type` = 'Article' 
WHERE
  `taggings`.`tag_id` IN (1, 3) 
  AND `taggings`.`taggable_type` = 'Article' 
GROUP BY
  articles.id 
HAVING
  (count(taggings.tag_id) = 2) 
LIMIT 11

As I said. What I expected would be that the result sets only contains the articles tagged with exactly the tags with the ids of 1 and 3, e.g. [1,3] but not decidedly not [1,3,5] or [1,2,3]. What I am frustratetingly getting however is the latter. The result set also contains the articles who have tags just IN(1,3) but over that do also have other tags.

Yours sincerly

von Spotz

Does noone have an idea why the count of tag_id isn’t applied to articles.ids ?