Topic: confused about redirect_to and render

i realize it is somewhat of a strange question but i'm new to webdevelopment, rails and ruby. i'm reading a book foundation rails 2, there i found the following piece of code:

  def create
    @toy = current_user.toys.build(params[:toy])
    if @toy.save
      redirect_to @toy
    else
      case params[:toy][:status]
        when 'LOST'
          render :file => 'toys/lost',
                 :use_full_path => true,
                 :layout => true
        when 'FOUND'
          render :file => 'toys/found'
                 :use_full_path => true,
                 :layout => true
      end
    end
  end

the question i have is why do we use render in the else clause, why can't we use redirect_to or vice verse, why do we use redirect_to in the if clause, why don't we use render?

help appreciated

Last edited by cyboman (2010-12-26 10:57:12)

Re: confused about redirect_to and render

A redirect starts at the top of the chain

typically the action is run, then view is rendered.

render skips the action, and just renders something with the data that exists from the last action.

In your case, once you've saved the Toy,  your done and ready for a new action,

But if your Toy didn't save,  you need to take corrective action or something,  with the EXISTING Toy that is defined,  you don't need a controller action to run at this point,  you just need to go back,  using the EXISTING data, and fix it,  so you just render something.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.