Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing error messages through flash

What is the best way to push error messages on redirect to?

I've previously used couple of approaches, but both of them has issue.

(1) Passing the entire object with error on flash and using error_messages_for:

  def destroy     if @item.destroy       flash[:error_item] = @item     end     redirect_to some_other_controller_path   end 

I found that this method causes cookie overflows.

(2) Passing a single error message:

  def destroy     if @item.destroy       flash[:error] = @item.full_messages[0]     end     redirect_to some_other_controller_path   end 

This way I only send a single error message, what if there are many? Does Anyone knows a better way?

like image 995
alexs333 Avatar asked Nov 24 '11 05:11

alexs333


People also ask

What is a flash error message?

What are flash messages? A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)

How does flash work Rails?

They are stored in the sessions cookie on the user's browser in order to persist for the next request. For the request following that one the flash hash clears itself out. They are not stored in the session cookie. They are merely associated with the session cookie.


1 Answers

Firstly, you can achieve what you're trying to do by setting a single sentence.

flash[:error] = @item.errors.full_messages.to_sentence 

I think you could also set it as the array without overflowing the cookie.

flash[:error] = @item.errors.full_messages 

But as the other guys say, flash is generally better off being used to return specific messages.

eg.

flash[:error] = "We were unable to destroy the Item" 

A common pattern is as such.

def some_action   if @record.action     flash[:notice] = "Action performed successfully"     redirect_to @record         else     flash[:error] = "Action failed"     render :action => "some_action"   end end 

Namely, we have two paths.

  1. Action succeeds. We redirect.
  2. Action fails. We show a page, flash an error, and have @record.errors on hand to call error_messages_for(@record) if we so wish.
like image 188
Matthew Rudy Avatar answered Sep 19 '22 10:09

Matthew Rudy