-1

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]
2
  • Please share how exactly you use Postman to send that data to your application and how exactly the log file entry for that request looks like. Commented Mar 10, 2022 at 11:41
  • Guys have been able to solve the issue: if params[:topics].present? @param=[params[:topics]] @json=JSON.parse("#{@param[0]}") p @json[0] @p= @json.each do |topic| if topic.key?('id').present? @w= Topic.find(topic['id']).update(topic) else @regex= @course.topics.create!(topic) end end end end Commented Mar 10, 2022 at 14:46

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

13 Comments

Thanks the array is generated from the api, can you please post an image
how do i get the attributes from the API request? Dynamically and pick them from attributes_list
Hey @spickermann, thanks for answering my question, However i have edited the question, i want to add these records from Rails API to the database, How do i get those attributes sent in the request from the API via Postman?
I am running into this error each time i try to run the above code: NoMethodError (undefined method `key?' for "[{\"name\"":String):
NoMethodError (undefined method `key?' for "[\"330087\"]":String):
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.