Rails 3 many to many query condition

前端 未结 3 575
名媛妹妹
名媛妹妹 2021-01-22 20:36

I\'m trying to do a simple Post/Tags relation in rails 3. Everything working fine except when I want to query the Posts which are related to several tags. Basically I\'d like to

3条回答
  •  悲哀的现实
    2021-01-22 21:24

    I don't know if it will solve you problem but for complex queries like that I almost always just use Squeel.

    Then do something like this:

    @posts = Post.joins(:tags)
      .where{tags.name.like_any names_array}
      .group("post_id")
      .having("count(post_id) = #{names_array.size}")
    

    The SQL hopefully looks something like this

    SELECT "posts".* FROM "posts"
      INNER JOIN "tags" ON "tags"."post_id" = "posts"."id"
      WHERE (("tags"."name" LIKE "TagA" OR "tags"."name" LIKE "TagB"))
      GROUP BY post_id
      HAVING count(post_id) = 2
    

    If I remember squeel is pretty good at using ILIKE instead of LIKE depending on the database used. (atleast better than AR)

    Also you could do this using AR without squeel but I REALLY like some of the ideas and helpers that come with squeel like _all


    As for an explination...

    Assume I searched for TagsA and B.

    What that does is finds all the Posts with those tags.

    So you'll have something like:

    • PostA TagA
    • PostA TagB
    • PostB TagA
    • PostB TagB
    • PostC TagA

    Then it will group all those different Post results by the joined tags using post_id.

    • PostA TagA TagB
    • PostB TagA TagB
    • PostC TagA

    Then it will check the number of Tags the SQL line has by checking how many forgien_ids are present. Since A and B have 2 tags you know it matched all you input.

提交回复
热议问题