Leave a comment

How to Set Up Flash Hashes and Error Messages in Rails


So simple but so many do not use this. We have a legacy app that has NO error messages. Try to login with wrong email, it just does not work but no message to tell you why. Seems like this should be a standard thing.

christopher r dodd code

Notices

1. Setting a notice

Setting a flash notice is as easy as assigning it to the flash object

flash[:notice] = "The subject was created successfully"

Where should you put it?

A good place to put it is in the controller after the object successfully saves or is destroyed. For example:

def create
  @subject = Subject.new(subject_params)

  if @subject.save
    flash[:notice] = "Subject '#{@subject.name}' created Successfully"
    redirect_to root_path

  else
    render('new')
  end
end

2. Displaying the notice

If using Bootstrap and HAML, you can put this in the view where the user gets redirected to

-if !flash[:notice].blank?
  .row
    .notice.alert.alert-success
      =flash[:notice]

If you’re not using Bootstrap or HAML, try this:

<% if !flash[:notice].blank? %>
   
<% end %>

Errors

1. Write your validations

For there to be errors, you need validations. If you haven’t built validations, I suggest you do this now.

2. Generate a partial for displaying your…

View original post 62 more words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: