2014-04-27 56 views
0

比方说,我们有以下方面:验证错误消息未设置相关的记录

class Company 
    belongs_to :address, validate: true 
end 

class Address 
    validates :line1, presence: true 
end 

company = Company.new({ ... }) 
company.address = Address.new({ line1: '' }) 

company.save 

puts company.errors[:address] # nothing 
puts company.errors[:"address.line1"] # can't be blank 

我怎样才能让验证错误设置为相关记录和不将拥有记录?这使得嵌套表单更加复杂,因为这些表单重用部分更加困难。

我确实需要有:

puts company.address.errors[:line1] # can't be blank 

回答

0

custom validation methods

validate :check_address, :on => :create 

def check_address 
    if self.address.line1.blank? 
    errors.add(:line1, "Please fill line 1.") 
    end 
end 
+0

感谢您的回答! – Viorel

+0

对于自定义验证器来说这并不是真正的必要,因为默认行为是做我想要的。验证错误也被设置为关联记录,不仅仅是为了拥有记录。无论如何,errors.add(“请填写行1”)应该是errors.add(:line1,“请填写行1”。) – Viorel

0

显然它的工作如预期。只是在我的代码中遇到困难让我觉得它没有。现在感到惭愧......