【问题标题】:No implicit conversion of symbol into integer while rendering JSON from nested model从嵌套模型渲染 JSON 时没有将符号隐式转换为整数
【发布时间】: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


【解决方案1】:

看:

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

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

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

另外,我认为包含也在错误的位置。 :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

【讨论】:

  • 这个问题解决了你的问题@Sudeep Ghimiray
  • 它解决了“TypeError 没有将 Symbol 隐式转换为 Integer”的问题,但它仍然没有获取 item_images。
  • @SudeepGhimiray 我现在用另一个修复更新了答案。
  • @Nathan Kontny 谢谢
猜你喜欢
  • 1970-01-01
  • 2017-04-12
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多