這是我正在接收的資料,如果陣列中不存在 id,我想添加新記錄,如果陣列中沒有 id,也更新記錄
我的模型:課程< ApplicationRecord has_many:主題belongs_to:用戶端
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]
uj5u.com熱心網友回復:
我會在一個條件下做到這一點:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440695.html
下一篇:非阻塞反引號
