使用accepts_nested_attributes_for时,Rails会重复验证错误

pin*_*ngu 2 validation ruby-on-rails

我有三个模型,事件,地址和县,这样设置.

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
Run Code Online (Sandbox Code Playgroud)

它们都是通过一种形式创建的,它可以正常工作,直到验证它们为止.如果县空白,那么我得到2个验证错误:

County can't be blank
Address is invalid
Run Code Online (Sandbox Code Playgroud)

我可以理解为什么会发生这种情况,但只需要第一个验证错误"县不能为空".

有关如何实现这一点的任何想法吗?

Sye*_*Ali 5

请尝试以下方法:

  1. 在Address模型中,您有下面给出的帮助方法,删除:

validates_associated:county

  1. 在县模型位置,添加以下内容:

validates_associated:地址

编辑:看起来你已经命中:https: //rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/5632-validates_associated-should-be-allowed-to-not-create-an-error #票5632-2

你可能想要反应那个bug ......