我试试宝石validates_operator。我需要为这个验证定制我的消息:
验证:arrival_date,:departure_date,重叠:{ 经营范围:“place_id” message_title:“错误”, Message_content:“不可能为这个日期预订这个地方”}
但我有一个简单表格的默认信息:“请检查下面的问题”
为了未来的答案。
发布于 2017-03-07 13:12:02
还可以创建验证模型状态的方法,并在错误集合无效时将消息添加到错误集合中。然后,您必须使用names (API)类方法注册这些方法,并传入验证方法名称的符号。
您可以为每个类方法传递多个符号,相应的验证将以与已注册的顺序相同的顺序运行。
有效的?方法将验证错误集合是否为空,因此当您希望验证失败时,您的自定义验证方法应该向它添加错误:
class Invoice < ApplicationRecord
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end
def discount_cannot_be_greater_than_total_value
if discount > total_value
errors.add(:discount, "can't be greater than total value")
end
end
end默认情况下,每次调用有效时,此类验证都会运行吗?或者保存对象。但是,还可以通过为these方法提供一个:on选项来控制何时运行这些自定义验证,方法是::create或:update。
class Invoice < ApplicationRecord
validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
end
endhttps://stackoverflow.com/questions/42648974
复制相似问题