0

I have a Store model, which has an id and other fields. I have a Product model which has an id and other field To join them I use Amount model. Here are the models:

class Product < ApplicationRecord
    has_many :amounts
    has_many :stores, through: :amounts
end

class Store < ApplicationRecord
    has_many :amounts
    has_many :products  , through: :amounts
end

class Amount < ApplicationRecord
    belongs_to :store
    belongs_to :product
end

Amount has in_stock property. I want my json to look like this:

{stores: [
    {"id": 1,
     "name": "New Store",
     "products": ["id": 1, "name": "Toothbrush", "in_stock": 4000]}
]}

I tried render json: {stores: stores}.to_json(include: :products), I also tried a nested include but it didn't work as well, it showed output for all amounts

2 Answers 2

2

Based on your comments on my original answer (which shows in stock comes from the Amount model) you can include amounts in the includes relation which would be a cleaner solution and more performant...

output = Store.all.includes(amounts: :product).map do |store|

  { id: store.id, name: store.name,
    products: store.amounts.map do |amount|
     { id: amount.product.id, name: amount.product.name, in_stock: amount._in_stock }
    end
  }

end.to_json
Sign up to request clarification or add additional context in comments.

Comments

2
output = Store.all.includes(:products).map do |store|

  { id: store.id, name: store.name,
    products: store.products.map do |product|
     { id: product.id, name: product.name, in_stock: product.in_stock }
    end
  }

end.to_json

This builds an array of store hashes, each store hash has an array of products, and the hash is converted to json.

2 Comments

there's no method in_stock for product
This works, but { id: product.id, name: product.name, in_stock: store.amounts .where(:product_id => product.id) .first ._in_stock } end } `

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.