仅使用一条错误消息进行Rails组验证

时间:2011-11-13 01:25:00

标签: ruby-on-rails ruby-on-rails-3 validation

模型中的以下验证代码:

validates :formatted_address, :zip, :city, :state, :country, :presence => true, :message => "is incomplete. Please enter full address."
当任一字段为空时显示

。我们现在说:addresscountry为空,显示2个错误:

Formatted Address is incomplete. Please enter full address.
Country is incomplete. Please enter full address.

如果验证的任何一个字段不存在,我如何将验证中的错误消息分组为只显示一条错误消息?

Address is incomplete. Please enter full address.

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用validate macro编写自己的验证器:

validate :has_complete_address

#...

private
def has_complete_address
    # Check that everything is there and
    # call self.errors.add to store an error
    # message if something is wrong.
end