【问题标题】:Ruby on Rails how to process the JSON Array which doesnt have a nameRuby on Rails 如何处理没有名称的 JSON 数组
【发布时间】:2020-06-12 11:33:49
【问题描述】:

我想要一个创建端点,它获取一个 JSONArray 并创建多个坐标对象(它有 2 个属性纬度和经度),但问题是我的示例 JSONArray 没有名称标签。如何声明 create 需要这种 JSOnArray,遍历这个 JSONArray 并访问数据?

示例 JSON

[{ "latitude": 32.9377784729004, "longitude": -117.230392456055 },
{ "latitude": 32.937801361084, "longitude": -117.230323791504 },
{ "latitude": 32.9378204345703, "longitude": -117.230278015137 },
{ "latitude": 32.9378204345703, "longitude": -117.230239868164 },
{ "latitude": 32.9378318786621, "longitude": -117.230209350586 },
{ "latitude": 32.9378814697266, "longitude": -117.230102539062 },
{ "latitude": 32.9378890991211, "longitude": -117.230072021484 },
{ "latitude": 32.9379081726074, "longitude": -117.230018615723 },
{ "latitude": 32.9379005432129, "longitude": -117.22998046875 },
{ "latitude": 32.937931060791, "longitude": -117.229949951172 },
{ "latitude": 32.9379615783691, "longitude": -117.229919433594 }]

这就是类的样子

class Trace < ApplicationRecord
  has_many :gps_coordinates
end
class GpsCoordinate < ApplicationRecord
  belongs_to :trace
end

和我的迁移

class CreateTraces < ActiveRecord::Migration[6.0]
  def change
    create_table :traces do |t|
      t.string :gps_coordinates
      t.timestamps
    end
  end
end
class CreateGpsCoordinates < ActiveRecord::Migration[6.0]
  def change
    create_table :gps_coordinates do |t|
      t.float :latitude
      t.float :longitude

      t.references :trace, foreign_key: true
      t.timestamps
    end
  end
end

我想要做的代码是

def create
    trace1 = Trace.create();
    params[].each do |latitude, longitude|
      GpsCoordinate.create!(latitude: latitude, longitude: longitude, trace_id: trace1.id())
    end

    render json: trace1, status: :created

  rescue ActiveRecord::RecordInvalid => e
    render json: e.message, status: 501
  end

但我不知道如何声明我将获得一个 JSONArray 到终点,以便我可以对其进行迭代以及如何在没有名称的情况下进行迭代。

【问题讨论】:

  • 我不确定你在问什么。如果数组是 json 的根目录,则不需要按名称访问它。
  • 我需要通过我的创建端点获取 JSONArray 并从中读取元素。从昨天开始我一直在搜索,但找不到如何遍历这个数组并访问数据。所有其他解决方案都使用名称标签,当我在没有名称标签的情况下执行相同操作时,它就不起作用了。我是 Ruby on Rails 的新手。我正在努力理解。
  • 也许显示一些实际代码会有所帮助。
  • 好的,我现在正在编辑,谢谢 :)
  • 我希望现在更清楚我想要做什么

标签: ruby-on-rails json ruby


【解决方案1】:

假设您的创建路由是 POST 并且您通过 POST 请求正文传递 JSON 数据,您应该能够使用 request.body 访问它并使用 each 方法对其进行迭代。

【讨论】:

  • 谢谢它也有效,但我用 params["_json"] 解决了它。每个都做 |trace|
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 1970-01-01
相关资源
最近更新 更多