Fellow Stranger
Fellow Stranger

Reputation: 34013

Get children of a collection of parents with ActiveRecord

I have a Category model and Post model with a one-to-many relationship.

I'd like to have all posts for a certain set of categories.

I want the result to be an ActiveRecord object to be able to do further queries.

Right now I'm using .map like so

categories.map{|c| c.posts.order(position: :asc)}

Upvotes: 3

Views: 1669

Answers (2)

Pascal
Pascal

Reputation: 8637

First find all the categories that you are interested and get the ids:

category_ids = Category.where('name like ?', '%foo%').pluck(:id)

Then just query for the Posts where the category_id is included in this list of ids:

posts = Post.where(category_id: category_ids)

This is a AR object, so you can keep adding order or where and so on:

posts.order(position: :asc)

Upvotes: -2

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Use embedded query to Posts, as follows:

Post.where(category_id: Category.all.pluck(:id)).order(position: :asc)

Upvotes: 4

Related Questions