未为关联记录设置验证错误消息

时间:2014-04-27 08:03:07

标签: ruby-on-rails ruby-on-rails-4

假设我们有以下背景:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

显然它确实按预期工作。我的代码只是一个障碍让我觉得它没有。现在感到惭愧......