2

I have three models, Event, Address and County, that are set up like this.

class Event < ActiveRecord::Base
     has_one :address
     accepts_nested_attributes_for :address, :allow_destroy => true


     validates_presence_of :address
     validates_associated :address
end

class Address < ActiveRecord::Base
     belongs_to :county, :event


     validates_presence_of :county
     validates_associated :county
end

class County < ActiveRecord::Base
     has_many :addresses

     validates_presence_of :name, :allow_blank => false
end

They are all created through one form, and it works fine until it comes to validating them. If the county is left blank, then i get 2 validation errors:

County can't be blank
Address is invalid

I can understand why this is happening, but only need the first validation error "County can't be blank".

Any ideas on how to acheive this please?

2 Answers 2

5

Try the following:

  1. In the Address model you have the helper method given below, remove it:

validates_associated :county

  1. In the County model place, add the following:

validates_associated :addresses

EDIT: looks like you've hit: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/5632-validates_associated-should-be-allowed-to-not-create-an-error#ticket-5632-2

You may want to reactive that bug ...

Sign up to request clarification or add additional context in comments.

Comments

1

Basic solution

You can try this in your view:

<% @event.errors.full_messages.each do |msg| %>
  <% unless msg.end_with?('is invalid') %>
  <li><%= msg %></li>
  <% end %>
<% end %>

But this code doesn't change errors.count on base model.

Alternative solution

You can clean up erorrs object from unnesessary errors in your controller (or whatever):

@event.errors.values.each {|v| v.delete_if{|message| message == "is invalid"} }

This code will produce this errors hash:

{:"address.county"=>["can't be blank"], :address=>[]}

So @event.errors.count will return 1 instead of 2.

5 Comments

Thanks Viacheslav, this works fine, but I can't help feeling this must be a common problem, and there should be a more elegant solution to supress the duplicates.
Then you can remove validates_associated :address from your model. Event would fail to save and you drop this is invalid message.
Sorry Viachesla, I didn't understand your last comment.
The goal was to remove the error. Your solution is in order to raise the exception still but to hide it
@NunoCosta hm, you are right. But for now it would be hard to reproduce original problem due to passed years. And here is accepted answer.

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.