I am developing an eCommerce App. I have a model Category which is divided into Category & Sub-Category through a self-join of same class as follow:
class Category < ApplicationRecord
enum kind: %i[category sub_category]
has_and_belongs_to_many :products
has_many :sub_categories, -> { where kind: 'sub_category' }, :class_name => "Category", :dependent => :destroy, :foreign_key => "parent_id"
belongs_to :parent_category, -> { where kind: 'category' }, :class_name => "Category", optional: true, :foreign_key => "parent_id"
scope :with_products, -> { joins(:products).distinct }
end
My Model Product is as follow:
class Product < ApplicationRecord
has_and_belongs_to_many :categories, -> { where(kind: :category) },:class_name => "Category", source: :categories
has_and_belongs_to_many :sub_categories, -> { where(kind: :sub_category) },:class_name => "Category", source: :categories
end
I want to load the Categories (of kind category) with scope with_products and want to eager load the category sub_categories (of kind sub_category) also with scope with_products
I have tried both below approaches but always get an error
Category.category.with_products.includes(:sub_categories).where(sub_categories: {id: Category.sub_category.with_products.ids})
and
Category.category.with_products.includes(:sub_categories).where(sub_categories: {id: Category.sub_category.with_products.ids}).references(:sub_categories)
Is there a solution or Rails way for this kind of eager loading with a condition/scope where associations is of same class?