Rails:包括通过关联嵌套

问题描述 投票:0回答:2

我有一个商店模型,它有一个id和其他字段。我有一个具有id和其他字段的Product模型要加入它们我使用Amount模型。以下是模型:

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

金额有in_stock财产。我希望我的json看起来像这样:

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

我试过渲染json:{stores:stores} .to_json(包括:: products),我也尝试过嵌套的include但是它也没有用,它显示了所有金额的输出

ruby-on-rails json
2个回答
1
投票

基于您对我的原始答案的评论(显示库存来自Amount模型),您可以在包含关系中包含金额,这将是一个更清洁的解决方案和更高性能......

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

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

这构建了一个商店哈希数组,每个商店哈希都有一个产品数组,并且哈希转换为json。

© www.soinside.com 2019 - 2024. All rights reserved.