【问题标题】:Archive .json import on rails api在 rails api 上存档 .json 导入
【发布时间】:2021-12-23 04:40:57
【问题描述】:

我在导入 .json 文件并将其中的数据保存在 api 数据库中时遇到问题。我的代码是这样的:

  def create
    content = JSON.parse(File.open(params[:products]).read)
    @product = Product.new(content)
    if @product.save
      render json: { message: 'Produto Salvo', data: @product }, status: 200
    else
      render json: @product.errors, status: :unprocessable_entity
    end
  end

文件(products.json)包含以下数据:

[{
  "title": "Brown eggs",
  "type": "dairy",
  "description": "Raw organic brown eggs in a basket",
  "filename": "0.jpg",
  "height": 600,
  "width": 400,
  "price": 28.1,
  "rating": 4
}, {
  "title": "Sweet fresh stawberry",
  "type": "fruit",
  "description": "Sweet fresh stawberry on the wooden table",
  "filename": "1.jpg",
  "height": 450,
  "width": 299,
  "price": 29.45,
  "rating": 4
}]

当我实现该方法时,所有字段都保存为 NIL:

#<ActiveRecord::Relation [#<Product id: 3, title: nil, product_type: nil, description: nil, filename: nil, height: nil, width: nil, price: nil, rating: nil, created_at: "2021-11-10 14:15:11.261454000 +0000", updated_at: "2021-11-10 14:15:11.261454000 +0000">]>

如何保存正确填写的数据?

【问题讨论】:

    标签: ruby-on-rails json ruby api


    【解决方案1】:

    看起来您正在阅读多个产品的数组?

    我建议在设置 content 和设置 @product 的位置之间插入 binding.pry

    content的值贴到这里,我想解决办法就会很清楚了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多