Flashing validation messages

Hi,

One thing which I've noticed with the default scaffold setup is that
when validating the model after a post, if there are errors they are
shown immediately (there is no redirect in between). I think it is
always better to do a redirect after a post so what is the DRYest way
to flash my error messages?

Thanks,
Abdullah

@flash[:error] = @object.errors.full_messages.join("<br />")

Just a quick hack.

I don’t see why redirecting after the post is necessary here… the record insertion failed. Refreshing the page would only result in the same error message coming back up. Rules like “always redirect after a post” should depend on the situation and not be requirements.

Hi Brian,

I think it is almost always necessary because otherwise if the user
tried to hit refresh after an invalid post the browser will try to
repost the data (usually giving you an error message first). This
approach gets rid of that. By the way here is what I decided to use:

def signup
    @user = flash[:user] || User.new
    if request.post?
      @user = User.new(params[:user])
      if @user.save
        flash[:notice] = "User #{@user.name} created"
        redirect_to home_url and return
      end
      flash[:user] = @user
      redirect_to :action => 'signup'
    end
  end

It works great but if anyone knows of a better way please let me know
(mainly I don't like how I have to reassign user if it's a post). And
the reason I flash user when validation fails is because that instance
has all the error messages attached to it.

Thanks,
Abdullah

With that approach you’ve doubled the resource load on your app when errors occur.

You need to do User.new twice now… because you’ve done it once to process the error and then once again after the redirect. Plus you’ve invoked the controller twice.

That’s why it’s not a good method to use in all circumstances. Sure it doesn’t matter on small sites, but it matters greatly on sites with lots of traffic. That’s the reason the default scaffolding uses the approach it does.

You have a point, I checked almost every large site I could think of
(gmail, yahoo, ebay, amazon, youtube, and several others) and the only
one that redirected after an error (in the login) was ebay. I do feel
it really helps out with usability though, so I'll try to test the
performance once I have time.

Thanks,
Abdullah