簡體   English   中英

我如何在數組中添加新記錄並從數據庫 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 Course < ApplicationRecord has_many: topics belongs_to:user end

class Topic < ApplicationRecord belongs_to:course belongs_to:user end

class User < ApplicationRecord has_many:courses has_many:Topics end

這是我通過 PostMan 從 Rails API 收到的數組 [ { "title": "Topic Name", "path_url": "https://resource-asws-path-url" }, { "id": 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM