In my app, I have the ability to create "lessons", and each lesson contains several "components". Right now, I'm trying to implement the ability to create a lesson from a template so it would duplicate/recreate the components from the template to the new lesson.
The data structure of my component is something like this:
{
id: 123,
type: Section,
content: "abc",
section_id: null
},
{
id: 124,
type: Question,
content: "abc?",
section_id: 123
},
{
id: 125,
type: Section,
content: "defg",
section_id: null
},
{
id: 126,
type: Outcome,
content: "defg?",
section_id: 125
},
Desired outcome:
{
id: 993,
type: Section,
content: "abc",
section_id: null
},
{
id: 994,
type: Question,
content: "abc?",
section_id: 993
},
{
id: 995,
type: Section,
content: "defg",
section_id: null
},
{
id: 996,
type: Outcome,
content: "defg?",
section_id: 995
},
You can see that there's an association between the Question/Outcome and the Section through section_id.
In my lesson model, I'm looping through the components of a template and taking their attributes for the newly created lesson components.
class Lesson
attr_accessor :lesson_template_id
# == Callbacks ==============================
after_create :create_template_components, if: :lesson_template_id_present?
def lesson_template
if @lesson_template_id != ''
LessonTemplate.find(@lesson_template_id)
else
nil
end
end
private
def lesson_template_id_present?
!!@lesson_template_id
end
def create_template_components
if lesson_template
lesson_template.components.each do |c|
self.components.create!({
type: c.type,
content: c.content,
section_id: c.section_id
})
end
end
end
But the problem is that the section_id is incorrect because the newly create sections would have a new/different id. How can I revise my model to make sure the components are created properly?
section_id: c.section_idis wrong always? Sorry I am not getting the problem. Could you tell me the more?create_template_components, thesection_idwill always be 123 (for example), even though thesection_idwill be new.