# passing information between #new and #create in a restfull rails app can be
# a bit tiresome - i don't really want to pass errors from #create over to
# #new using something hacky like flash or query string vars.  in fact,
# #create and #new are intimately connected and using a pattern like this
# let's them be so, allowing restful routes while also allowing a single
# method to be written for the new/create sequence.  i cut out the 'wants xml'
# and other methods for clarity, but you can work that out for your self.
# note in the example that an object *graph* is being produced, not just a
# single object, which normally confuses the situation, since you have to pass
# errors from multiple objects from #create to #new, but doesn't at all in
# this case.
#


class ClassroomsController < ApplicationController

# GET /classrooms/new
# GET /classrooms/new.xml
#
  def new
    create_new
  end

# POST /classrooms
# POST /classrooms.xml
#
  def new
    create_new
  end

protected
  def create_new
    @classroom = Classroom.new
    @teacher = Teacher.new
    @location = Location.new
    @classroom.teacher = @teacher
    @classroom.location = @location

    if request.get?
      render :template => 'classrooms/new'
      return
    end

    transaction do
      @classroom = Classroom.create(params[:classroom])
      @location = Location.create(params[:location])

      begin
        @teacher = User.find(params[:teacher][:id])
      rescue Object => e
        @teacher = Teacher.new
        @teacher.errors.add 'id', 'No teacher specified'
      end

      records = [@classroom, @location, @teacher]

      unless records.all?{|record| record.errors.empty?}
        @classroom.destroy rescue nil
        @location.destroy rescue nil
        render :template => 'classrooms/new'
        return
      else
        @classroom.teacher = @teacher
        @classroom.location = @location
      end
    end

    redirect_to classrooms_path
  end
end