Cannon Moyer
Cannon Moyer

Reputation: 3164

Include Child Record Count in json Rails

I'm trying to include a item_count field in a json response on Rails. I have a list of Categories and each of those records has one or more Items.

Here is my current index.json.jbuilder file:

json.array! @categories, partial: 'categories/category', as: :category

And the _category.json.jbuilder partial

json.extract! category, :id, :name, :created_at, :updated_at
json.url category_url(category, format: :json)

I want to include category.item_count in the response but I'm not exactly sure how to do this. Thanks in advance.

Upvotes: 1

Views: 278

Answers (1)

MrShemek
MrShemek

Reputation: 2483

You can add item_count to the partial like this:

json.item_count category.items.count

However, for each category, it will execute an additional query (to get the number of items):

SELECT COUNT(*) FROM `items` WHERE `items`.`category_id` = ID

Upvotes: 1

Related Questions