'Rails API--- Update Course with topics and Topics with subtopics
I need help need to create topics with nested array subtopics and under one API endpoint. I would like where i can update topics under a course by submitting course_id, if the topic is not present i created new topic and if topic_id is present i can update the topic or and i supply empty array i delete all topic_ids and the same goes for subtopic. The challenge is that i have managed the topics and now i need subtopics under one endpoint for Rails api to update and create and delete.
sample of array i want to update under topics which are under a course
[
{
"topic_id" : 636015,
"name": "Topic 1",
"body": " Great Lord"
"sub_topics" : [
{
"title": "Sub Topic 1",
"url_path": "https:/dasdasdasdas"
}
]
}
]
Endpoint -----
def save_changes
require 'json'
@course = Course.find(@course_id)
if @course.present?
@update= update_course
else
end
if params[:topics].present?
@x= JSON.parse(params[:topics]).each do |topic|
if topic.key?('id')
@topic= @course.topics.find(topic['id'])
@topic_id= @topic.id
p @topic_id, " this topic ID exists"
@topic.update(topic)
else
@course.topics.create!(topic)
end
end
end
if JSON.parse(params[:topics])==[]
@course= Course.find(@course_id)
@delete= @course.topics.where(course_id: @course.id)
@delete.each do |topic|
topic.destroy
end
end
if params[:subtopics].present?
@x= JSON.parse(params[:subtopics]).each do |subtopic|
@topic= Topic.find(@topic_id)
if subtopic.key?('id')
@subtopic= @topic.subtopics.find(subtopic['id'])
puts @subtopic.title
@subtopic_id= @subtopic.id
p @topic_id, " this sub topic ID exists"
@subtopic.update(subtopic)
else
@topic.subtopics.create!(subtopic)
end
end
end
if JSON.parse(params[:subtopics])==[]
@delete= @topic.subtopics.where(topic_id: @topic.id)
@delete.each do |subtopic|
subtopic.destroy
end
end
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
