0

I originally asked this question about acts_as_tree but it seems to be more general so I'm rephrasing it a bit here. I have a model "category" using acts_as_tree. I often find myself needing to join it with other models for various queries, but I don't know how to use the provided scopes such as children, ancestors, siblings, descendants to create the conditions that I need.

Concrete example:

class Category < ActiveRecord::Base
  acts_as_tree
  has_many :photo
end

class Photo
  belongs_to :category
end

cat = Category.first

How can I query for all the photos of children of cat or all the photos of its siblings? Seems like I need something like:

Photo.joins(cat.children)
Photo.joins(cat.siblings)

which I know is not a valid code.

shaimo
  • 376
  • 3
  • 17

1 Answers1

0

Since act_as_tree doesn't really use scopes but methods that return results, you can do it like:

class Photo
  belongs_to :category

  scope :from_category, -> (category) {
      joins(:category).where(category: category)
  }
end

cat = Category.first

Photo.from_category(cat.children)
Photo.from_category(cat.siblings)

And that should work.

Francisco Soto
  • 10,277
  • 2
  • 37
  • 46