Search code examples
ruby-on-railsrolesnested-resources

Create Nested Resource at same time as Parent


I have three models Session, Attendee, Role. Attendee is nested within Session and Role is a separate model.

I want to be able to Create a new Session and when the session is created a attendee is created for that session that has the Role "Owner".

I am drawing a blank on two things:

1) How to add a Attendee to the Session upon creating

2) How to find the ID for the role "Owner" and add it as a parameter for the Attendee.

Look forward to hearing from y'all!

:D


Solution

  • Couple of options.

    Add it to after_create or before_create callback on Session.

    class Session
       after_create :create_attendee
    
       def create_attendee
          Attendee.create(session: this)
       end
    end
    
    class Session
       before_create :build_attendee
    
       def build_attendee
          this.attendees << Attendee.new(...)
       end
    end
    

    Create it explicitly while creating your session object

    session = Session.new(..)
    session.attendees << Attendee.new(..)
    session.save