Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Last active November 28, 2017 11:14
Show Gist options
  • Save BideoWego/1c649b188f2da627d2e2 to your computer and use it in GitHub Desktop.
Save BideoWego/1c649b188f2da627d2e2 to your computer and use it in GitHub Desktop.
Rails helper to get validation error messages for a given object or an optional field on that object. Also a view partial to output those errors.
<% if object.errors.present? %>
<div class="alert alert-danger">
<%
field ||= nil
error_messages_for(object, field) do |error|
%>
<%= error %>
<br/>
<% end %>
</div>
<% end %>
module ApplicationHelper
def error_messages_for(object, field=nil)
errors = field ? object.errors[field] : object.errors.full_messages
errors.each do |error|
yield(error)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment