0

I have posts habtm users and habtm tags. I need to find posts, that have both tags "cats" and "cute", so I'm trying to use:

current_user.posts.includes(:tags).where("tags.title = ? AND tags.title = ?", "cats", "cute")

and it returns an empty array, though the same query with OR instead of AND works fine. And the other question, is it actually a correct way of doing it? My worry is that the actual MySQL request will become very big and heavy, is there a better option?

Thanks a lot in advance.

Edit: here is a SQL query the line of code above creates:

SQL (0.9ms)  SELECT `posts`.`id` AS t0_r0, `posts`.`provided_id` AS t0_r1, `posts`.`uid` AS t0_r2, `posts`.`content` AS t0_r3, `posts`.`image` AS t0_r4, `posts`.`small_image` AS t0_r5, `posts`.`provided_created_at` AS t0_r6, `posts`.`latitude` AS t0_r7, `posts`.`longitude` AS t0_r8, `posts`.`created_at` AS t0_r9, `posts`.`updated_at` AS t0_r10, `posts`.`provider` AS t0_r11, `tags`.`id` AS t1_r0, `tags`.`title` AS t1_r1, `tags`.`created_at` AS t1_r2, `tags`.`updated_at` AS t1_r3 FROM `posts` LEFT OUTER JOIN `posts_tags` ON `posts_tags`.`post_id` = `posts`.`id` LEFT OUTER JOIN `tags` ON `tags`.`id` = `posts_tags`.`tag_id` INNER JOIN `posts_users` ON `posts`.`id` = `posts_users`.`post_id` WHERE `posts_users`.`user_id` = 2 AND (tags.title = 'cats' AND tags.title = 'cute')
4

1 回答 1

1

Found the solution here: finding Post associated with both of two Categories in Rails 3 without custom SQL

Thanks a lot for trying to help anyway.

于 2013-11-03T17:09:34.627 回答