我有以下 Controller :
# orders_controller.rb
def update_quantity
@product = Product.by_id(params[:product_id])
@product_details = ProductDetail.availables.by_id(params[:product_id])
respond_to do |format|
format.json { render :json => @product.to_json( { :include => [ :current_price, :product_details ] } ) }
end
end
我只想返回包含产品数据的 JSON,包括当前价格和 products_details,但只是可用的详细信息(库存)。
产品和 current_price 运行良好,但如果我使用 :product_details,rails 包含所有详细信息,我希望包含在@product_details 变量中。
谢谢
最佳答案
我不确定我是否理解您的问题。如果 product_details
不起作用,试试这个:
def update_quantity
@product = Product.by_id(params[:product_id])
respond_to do |format|
format.json {
render :json => @product.to_json(
{
:include => [ :current_price ],
:methods => [ :product_details ]
}
)
}
end
end
在您的 Product
模型中添加:
def product_details
ProductDetail.availables.by_id(self.id)
end
如果您只需要 product_details
的某些字段:
respond_to do |format|
format.json {
render :json => @product.to_json(
{
:include => [
:current_price,
product_details: {
only: [
:field1,
:field2
]
}
]
}
)
}
end
关于ruby-on-rails - Rails 4 - 简单地在另一个 JSON 中包含多个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35091432/