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:
@categories = Category.includes(:products).where(products: { user_id: current_user.id })
@categories.as_json(include: :products)
#Category that has no product is not included
class Product < ApplicationRecord
belongs_to :user
belongs_to :category
end
class Category < ApplicationRecord
has_many :products
end
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments