从嵌套模型渲染 JSON 时没有将符号隐式转换为整数

No implicit conversion of symbol into integer while rendering JSON from nested model

我是 rails API 的新手。对于以下语法,我在 rails 服务器控制台中得到 "TypeError No implicit conversion of Symbol into Integer"。

def show
@product = Product.find(params[:id])
render json: @product.to_json(:include => 
  { :items => 
    { :only => 
      [:id, 
        :description, 
        :item_name, 
        :item_code, 
        :display_tag, 
        :price,
       {:include => 
        :item_images [:id, 
        :image_url]
      }
      ]
    }
  }
)
end

它应该在请求 URL 时显示 item_images 的数组以及项目(例如 http://localhost:4000/products/1)我的 JSON 是这样的:

{
"id": 1,
"product_name": "Foundation",
"description": "test",
"image_file_name": "text.jpg",
"image_content_type": "image/jpeg",
"image_file_size": 341279,
"image_updated_at": "2018-10-24T09:28:49.000Z",
"image_url": "http://localhost:3000/system/products/1/original/text.jpg",
"created_at": "2018-08-28T14:50:29.000Z",
"updated_at": "2018-10-24T09:28:50.000Z",
"items": [
    {
        "id": 6,
        "item_name": "LOTUS WHITE GLOW COMPAC POWDER",
        "item_code": "SF264",
        "display_tag": "New",
        "description": "SKIN WHITENING AND BRIGHTENING NOURISHING\r\nSUITABLE FOR ALL SKIN TYPES\r\nULTRA-FINE SILTY FORMULA\r\nSILKY SMOOTH AND DELICATE TEXTURE\r\nCONTAINS NATURAL PLANT INGREDIENTS CAN BLOCK THE INSIDE DARK",
        "price": "1250.0"
    },
    {
        "id": 7,
        "item_name": "Test",
        "item_code": "100",
        "display_tag": "New",
        "description": "lorem ipsum",
        "price": "200.0"
    }
]}

有什么帮助吗?

看:

{:include => :item_images [:id, :image_url]}

:item_images [:id, 不对。你的意思可能是这样的:

{:include => :item_images => {:only => [:id, :image_url]}}

另外,我认为 include 也在错误的位置。 :include 应该是另一个键,例如 :only 在该哈希中(现在 :include 在 :only 数组中)。所以这应该有效:

def show
  @product = Product.find(params[:id])
  render json: @product.to_json(:include => 
    { :items => 
      { :only => 
        [:id, 
          :description, 
          :item_name, 
          :item_code, 
          :display_tag, 
          :price
        ],
        :include => 
        {
          :item_images => {:only => [:id, :image_url]}
        }
      }
    }
  )
end