ruby-on-railserror-handlingdeviserails-flash

Consistent displaying of flash messages and model validation errors in Ruby On Rails


Do people use a unified system for displaying flash messages and model validation errors in their apps? or do you keep them separate?

Is there an accepted best practice? or would it be driven by where it visually makes sense to display them.

This question has come about after working with the devise gem, as it displays model errors for signing in through the flash, and I want to provide the user with a consistent experience.


Solution

  • After using the rails composer for a while -- http://railsapps.github.io/rails-composer/ -- I liked the way they formatted messages, and as a result I've picked up the habit, but this is largely preference.

    In the application layout call a = render 'messages' near the top under your header, someplace it makes sense for a user to took for a message.

    Then in the messages partial:

    - flash.each do |name, msg|
      - if msg.is_a?(String)
        %div{:class => "alert alert-#{name == :notice ? "success" : "error"}"}
          %a.close{"data-dismiss" => "alert"} ×
          = content_tag :div, msg, :id => "flash_#{name}"
    

    And I use simple_form, which gives in-line error messages for forms using f.error_notification .

    It gives a consistent look, error messages are always the same, notices are always the same, info is always the same. Just remember that if you're using modals, you'll need to add messages directly to the messages display to the modal body.