Last active
October 2, 2015 18:58
-
-
Save nacengineer/2301097 to your computer and use it in GitHub Desktop.
A little snippet to add to application_helper to handle errors in a rails 3.2 form. (requires HAML 4). This allows you to replace the generated error explanation at the top of your _form.haml partials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# create this in helpers/feedback_helper.rb | |
# use version 1 for haml (buggy) or version 2 for erb | |
# version 1 via haml | |
require 'haml' | |
module FeedbackHelper | |
def self.included(base) | |
base.class_eval do | |
include Haml::Helpers | |
extend Haml::Helpers | |
end | |
end | |
def explain_errors( model ) | |
init_haml_helpers | |
if model.present? && model.errors.any? | |
capture_haml do | |
haml_tag :h4 do | |
haml_concat <<-HERE_DOC | |
#{pluralize( model.errors.count, "error")} prohibited this | |
#{ model.class } from being saved: | |
HERE_DOC | |
end | |
haml_tag :ul do | |
model.errors.full_messages.each do |msg| | |
haml_tag :li, msg | |
end | |
end | |
end | |
end | |
end | |
end | |
# version 2 less buggy as its erb | |
module FeedbackHelper | |
# ERB ONLY | |
def explain_errors(model) | |
if model.present? && model.errors.any? | |
html = "" | |
html << content_tag(:h4) do | |
<<-HERE_DOC | |
#{pluralize( model.errors.count, "error")} prohibited this | |
#{ model.class } from being saved: | |
HERE_DOC | |
end | |
html << content_tag(:ul) do | |
model.errors.full_messages.each {|msg| | |
concat(content_tag(:li, msg, class: 'text-error')) | |
} | |
end | |
html.html_safe | |
end | |
end | |
end | |
# leverage this in your haml _form.haml partial with | |
= simple_form_for @object do |f| | |
= explain_errors @object | |
... |
Blows up with haml 4! Damn you!
fixed for haml 4
ugh. still broken. lol
the erb one works. the other one sometimes needs init_haml_helpers
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've tested this with DataMapper and ActiveRecord. It requires the errors method on a model so in data mapper it will require dm-validations.