【发布时间】:2018-10-30 16:23:18
【问题描述】:
我是 Rails API 的新手。对于以下语法,我在 rails 服务器控制台中收到“TypeError 没有将 Symbol 隐式转换为 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(例如 http://localhost:4000/products/1)时,它还应该显示 item_images 的数组,我的 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"
}
]}
有什么帮助吗?
【问题讨论】:
-
我真的会考虑使用 ActiveModel::Serializers、fast_jsonapi 或 jBuilder。在控制器中内联复杂的 JSON 结构并不理想。
-
您的 URL
http://localhost:4000/products/1没有任何帮助,可能会误导新手。如果该调用的结果是您的 JSON,那么只需将其删除。
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 rails-api