1

If there are semantic errors in the form (mostly from external API), I'd like to add an explanatory message, like so:

<%= semantic_form_for @order, :url => checkout_purchase_url, :html => {:class => 'payment'}, :wrapper_html => { :class => "field" }  do |f| %>
<% if f.has_errors? %>
    <p>There were errors that prevented your order from being submitted.  If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
    <%= f.semantic_errors %>
<% end %>
<% end %>

However, has_errors? is a protected method. Is there a way that I can do this? Thanks.

3 Answers 3

4

If you have nested attributes you won't see any errors associated with them. To ensure you get all base errors and any nested attributes errors. Make sure your model contains:

validates_presence_of :nested_object
validates_associated :nested_object

and in your form:

f.semantic_errors *f.object.errors.keys
Sign up to request clarification or add additional context in comments.

Comments

3

Not as hard as I thought. I fixed it by checking for errors on the object instead of the form:

<% if @object.errors.any? %>
    <p>There were errors that prevented your order from being submitted.  If you need assistance, please contact us toll-free at <strong>1-800-555-5555</strong>.</p>
    <%= f.semantic_errors %>
<% end %>

Thanks for those who viewed.

Comments

0

For completeness, here's an alternative approach if you want to show similarly helpful messages on each field:

= f.label :title
- if f.object.errors.any?
 .error = f.object.errors[:title].flatten.join(' and ')
= f.text_field :title

This gives a nicely formatted and easily-styled list of errors for each field. (You can use semantic_errors instead of object.errors if you prefer, same result.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.