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 thr开发者_StackOverflow中文版ough 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?
Try the following:
- In the Address model you have the helper method given below, remove it:
validates_associated :county
- 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 ...
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
.
精彩评论