有多种方法可以做到这一点。
你最简单的解决方案:
def check_depth
self.errors.add(:depth, "Issue with depth") if self.value > 2 # this does not support I18n
end
最干净的使用模型验证(您category.rb的顶部,只需添加):
validates :depth, :inclusion => { :in => [0,1,2] }, :on => :create
如果您的验证逻辑得到更复杂的,使用自定义验证程序:
# lib/validators/depth_validator.rb (you might need to create the directory)
class DepthValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, "Issue with #{attribute}") if value > 2 # this could evene support I18n
end
end
在使用此验证程序之前,编辑加载它,例如在初始化
# config/initializers/require_custom_validators.rb
require File.join('validators/depth_validator')
您需要重新启动您的轨道服务器更改后(和您在您的验证作出更改之后)。
现在,在您的产品类别型号:
validates :depth, :depth => true, :on => :create # the :on => :create is optional
问题将在@category.save
提高,所以你可以设置你的闪光的通知,像这样:
if @category.save
# success
else
# set flash information
end
哎呀,如果验证逻辑不太复杂,你甚至不需要自定义过滤器 - 将更新我的答案。 – emrass 2012-04-15 07:50:10
谢谢你提供的所有信息,我用它提供了最直接的答案,并且确实使用了I18n,所以我将使用自定义验证器。非常感谢你的努力。 – ruevaughn 2012-04-15 21:39:56
太棒了! I18n也将采用上述“最干净”的解决方案(选项2)。您只需在您的语言环境中为[en | de | ...]。errors.messages.inclusion进行翻译 - 或者在此处使用示例语言环境之一https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale作为基础。对于自定义验证器,而不是错误文本“mytext ...”放置一个符号,如:depth_not_in_range,并在[locale] .collaboration.errors.models.category.attributs.depth.depth_not_in_range中有翻译 – emrass 2012-04-15 22:09:35