1

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.