Search code examples
ruby-on-railsactiverecordhas-and-belongs-to-many

Populating HABTM relation when using where on said relation


Let's say I have a post model which has and belongs to many categories. When I pull a list of posts for a certain category (with id = 1) I do it like this:

posts = Post.includes(:categories).where(categories: { id: 1 })

Suppose the first post of this list belongs to 3 categories, however when I do:

posts.first.categories

... it only shows the category with id = 1.

Is there a way to populate all of the categories so that I don't have to do N + 1 when looping through the posts?


Solution

  • do it this way

    posts = Category.find(1).posts
    

    Now you have all the posts in the category, with all categories for each post available.