2

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?

Selim Alawwa
  • 742
  • 1
  • 8
  • 19
  • 1
    This might help: https://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children/18082147#18082147 you can discover what Rails will use as alias for your `sub_categories` reference by simply analyzing the SQL produced by `Category.joins(:sub_categories)`, then use this alias in your where clause – MrYoshiji Jan 25 '19 at 16:10
  • Thanks, I have read it, maybe I will do it in as SQL, but was was asking to use a scope on joined association not just a condition in a Rails way – Selim Alawwa Jan 25 '19 at 16:35
  • What is the SQL generated by `Category.joins(:sub_categories)`? – MrYoshiji Jan 25 '19 at 16:58
  • Category.category.joins(:sub_categories) generates -> Category Load (0.4ms) SELECT "categories".* FROM "categories" INNER JOIN "categories" "sub_categories_categories" ON "sub_categories_categories"."parent_id" = "categories"."id" AND "sub_categories_categories"."kind" = $1 WHERE "categories"."kind" = $2 LIMIT $3 – Selim Alawwa Jan 25 '19 at 23:13

0 Answers0