JBuilder dynamic keys for model attributes

倖福魔咒の 提交于 2019-11-29 06:16:15

问题


I'm trying to build a JSON file to access a product's variation via a variation code. Ideally, I could call variations.abcdefgh essentially asking to define a structure like this:

{
   "variations":{
      "abcdefgh":{
         "available":true,
         "price":"12.00"
      },
      "ijklmnop":{
         "available":false,
         "price":"25.00"
      }
   }
}

Doing something in products/show.json.jbuilder like

json.variations @product.variations

gives me formatting as such:

{
   "variations":[
      {
         "available":true,
         "price":"12.00",
         "product_code":"abcdefgh"
      },
      {
         "available":true,
         "price":"25.00",
         "product_code":"ijklmnop"
      }
   ]
}

maybe my JavaScript could be better, but I want something a little more accessible based on the product_code. The closest I've gotten has been

@product.variations.each do |variation|
   json.set! variation.product_code, variation
end

but I've yet to find a solution that will put these correctly formatted objects as children into a variations attribute. Anyone run into something similar before?


回答1:


json.set! :variations do
  @variations.each do |variation|
    json.set! variation.product_code do
      json.(variation, :available, :price)
    end
  end
end

^^ this should do it



来源:https://stackoverflow.com/questions/18154252/jbuilder-dynamic-keys-for-model-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!