如何在数组中添加新记录并从数据库中的数组更新记录 Rails API

How do i add new records in array and update records from an array in the data base Rails API

这是我正在接收的数据,如果 id 不在数组中,我想添加新记录,如果数组中没有 id,也更新记录

我的模特: class 课程 < ApplicationRecord has_many: 主题 belongs_to:用户 结束

class 主题 < ApplicationRecord belongs_to:课程 belongs_to:用户 结束

class 用户 < ApplicationRecord has_many:课程 has_many:主题 结束

这是通过 PostMan 从 Rails API 接收的数组 [ { "title" : "主题名称", “path_url”:“https://resource-asws-path-url” }, { “编号”:2311, "title" : "主题名称", “path_url”:“https://resource-asws-path-url” } ]

我是这样做的:

 if params[:topics].present?
                    attributes_list = [params[:topics]].to_s
                    attributes_list.each do |attributes|
                      if attributes.key?('id')
                        Topic.find(attributes['id']).update!(attributes)
                      else
                        Topic.create!(attributes)
                      end
                    end
I need to get attributes dynamically from the request from post under params[topics]

我会这样做的条件是:

if params[:topics].present?
  JSON.parse(params[:topics]).each do |topic|
    if topis.key?('id')
      Topic.find(topic['id']).update!(topic)
    else
      Topic.create!(topic)
    end
  end
end