Want to get all user's products by category including category that have no product

I have two models - parent and child, and parent has_many children, and I have an array of parents and want to retrieve all of the children for all of those parents including parent that have no children. Parent will render as_json and send to react components.

What is the cleanest way to get all categories with current_user's products including categories that have no product associated with them?

I want to view like this:

Category1

  • Product 1
  • Product 2

Category2

  • Product 1
  • Product 2

Category3

  • (empty)

I already try

@categories = Category.includes(:products).where(products: { user_id: current_user.id }) 
@categories.as_json(include: :products)

#Category that has no product is not included

Model

class Product < ApplicationRecord
  belongs_to :user
  belongs_to :category
end

class Category < ApplicationRecord
  has_many :products
end

1 answer

  • answered 2018-01-14 16:17 Phong Phan

    You can override as_json method

    Category.includes(:products).as_json(user_id: current_user.id)
    
    ## model/category.rb
    def as_json(options = {})
      json = serializable_hash(options)
      json['products'] = products.where(user_id: options[:user_id]).as_json
      json
    end