从嵌套模型渲染JSON时,不会将符号隐式转换为整数

时间:2018-10-30 16:23:19

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5 rails-api

我是Rails API的新手。我在Rails服务器控制台中收到“ TypeError没有将符号隐式转换为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)我的JSON时,它还应该显示item_images数组,例如:

{
"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"
    }
]}

有帮助吗?

1 个答案:

答案 0 :(得分:1)

查看:

{: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