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

Time:03-11

This is the data i am receiving and would want to add new records if the id is not present in the array and also update the records if there is no id in the array

my Models: 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

This is the array am receiving from Rails API via PostMan [ { "title" : "Topic Name", "path_url" : "https://resource-asws-path-url" }, { "id" : 2311, "title" : "Topic Name", "path_url" : "https://resource-asws-path-url" } ]

this is how am doing it:

 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]

CodePudding user response:

I would do that with a condition:

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
  • Related