0

I got a form like this

<%= form_for @checkout_form, url: checkout_path(@checkout_form), html: {class: 'details-form', method: :put} do |f| %>
    <%= f.fields_for :billing_address do |builder| %>
      <% error_class = @checkout_form.billing_address.errors[:phone].any? ? 'error' : '' %>
      <%= builder.text_field :phone, class: "text #{error_class}" %>
    <% end %>
<% end %>

Everything is working fine except for the error class. I'm not really sure how I can grab the errors for that specific field in that context.

If I try it like this I get

undefined method `errors' for nil:NilClass
Evo_x
  • 2,997
  • 5
  • 24
  • 40
  • 1
    this code is definitely incomplete, the `do` in the `f.fields_for :billing_address` line is not closed. Sure there's not another <% end %> line? Also, the error is pretty straightforward - billing_address is nil, check that it exists first. – jamuraa Mar 14 '14 at 02:55
  • I was missing the last end, yes. I didn't want to copy all other fields of the form in here because it already crashes at the first error class line. I just want to know how I can access the errors of the form field <%= builder.text_field :phone %> for example. – Evo_x Mar 14 '14 at 02:59

2 Answers2

0

Here's a resource for you: How to change the default rails error div "field_with_errors"

From my understanding, erroneous form fields are wrapped with this div: <div class="field_with_errors"></div> - if you're just trying to show a different style for the element (no message), why don't you just style this in your css?

#app/stylesheets/application.css
.field_with_errors input { border: 1px solid #ff0; }
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

The error message tells you that @checkout_form.billing_address is nil, as it is the only position where "errors" is called.

If it is nil, it can not have errors-strings attached.

You need to examine your controller and model.

Meier
  • 3,858
  • 1
  • 17
  • 46