Creating Multiple Associated Records After Creation of Parent Object

22 Views Asked by At

I have an application where users create Appointments, and each Appointment has a set of Skills attached to them through a Appointment_Skills table. There are about 50 or so Skills that I would like to attach to each appointment after creation. Because the appointment form is so large and there are so many things to track, I have the users create an Appointment with a minimal form, then redirect to the edit page where they have access to the whole appointment. I am using nested attributes to update the Appointment and Appointment_Skills in the edit form.

Appointment
  has_many :skills, through: :appointment_skills 
  has_many :appointment_skills
  accepts_nested_attributes_for :appointment_skills
end

AppointmentSkill
  belongs_to :skill
  belongs_to :appointment     
end

Skill

end

If I go ahead and create a few AppointmentSkills I can then use my edit form to update their attributes, but I'm not sure how to automatically create them after the parent is created.

I've thought about first getting a count of all the Skills and Ids, then using an after_create callback to create all the AppointmentSkills that would have the Skill Ids and Appointment Ids(of the appointment just created).

Is this possible? Is this a strange way of doing it?

1

There are 1 best solutions below

0
cjiro On

Ended up doing...

    after_create :assign_skills 

    def assign_skills
       skills = Skill.all
       skills.each do |skill|
       AppointmentSkill.create(:appointment_id => self.id, :skill_id => skill.id, :position => skill.priority)
    end
end