I have an event model. Each event can have multiple sessions.
I want to ensure that no model can exist without it having at least 1 session associated with it.
validates :sessions, :length => { :minimum => 1 }
The problem is - when I go to try to create sessions on a particular event by calling my model method:
create_sessions()
Which does something like :
sessions.create(event_id: id,date: x,day_of_the_week:x.strftime("%A"),classPin: pin)
for each of the dates the event will run.
It fails to save with the error:
ActiveRecord::RecordNotSaved in EventsController#create
You cannot call create unless the parent is saved
Of course - by this point the new event record has not yet been saved - so this association cannot yet be created due to create on an association not available until the parent is saved!
Therefore how does any validation between this kind of relationship work - because the validation occurs at save time....but I want to validate the count of sessions will be greater than 0 before we save the event!