2013-10-04 39 views
0

我有这样的模式:轨道4嵌套的验证工作不

class CompetitionEntry < ActiveRecord::Base 
    has_many :participants 
    has_one :address 
    has_many :music_programs 

    accepts_nested_attributes_for :address 

    accepts_nested_attributes_for :participants, :music_programs, 
    :allow_destroy => true, 
    :reject_if  => :all_blank 

end 

这一个:

class Participant < ActiveRecord::Base 
    belongs_to :competition_entry 
    has_one :birthplace 

    validates :name, :surname, :instrument, presence: true 
end 

现在的问题是,如果我创建一个新的参赛作品,它经历。 但是,如果我填入一个字段,即名称,那么它会出现一个错误!

这是怎么发生的?当所有都是空的时候它应该失败!

+0

什么是错误? – Agis

回答

0

当您使用accepts_nested_attributes_for,您可以创建participants记录的同时,该competition_entry记录,考虑到散列传递给competition_entry.create包含participants_attributes。当您仅传递名称时,它会验证要创建的参与者并失败,因为它没有surnameinstrument。当您将所有字段留空时,行为应该是相同的,但这不是因为您明确设置了:reject_if => :all_blank

:reject_if => :all_blank指出,如果blank?participant_attributes散列,那么在您不填充任何字段时会发生participant_attributes散列。接下来发生的事情是,competition_entry正在创建而没有尝试创建participant,因为accepts_nested_attributes_for被忽略。