这里非常基本的问题,我需要在我的分类模型上编写一个前过滤器,以确保深度永远不会超过2.这是我到目前为止所拥有的。
应用程序/模型/ category.rb
before_create :check_depth
def check_depth
self.depth = 1 if depth > 2
end
我需要它而不是将深度设置为1,只是为了返回错误消息,但我甚至无法使当前设置生效,我收到错误
undefined method `>' for nil:NilClass
所以,不是像我想要的那样将深度设置为一个,而是如何发送错误?任何帮助使当前功能为信息目的工作?提前致谢
答案 0 :(得分:5)
有多种方法可以做到这一点。
最简单的解决方案:
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')
您需要在更改后(以及在验证器中进行任何更改后)重新启动rails服务器。
现在在你的catagory模型中:
validates :depth, :depth => true, :on => :create # the :on => :create is optional
问题将在@category.save
上提出,因此您可以设置闪存通知:
if @category.save
# success
else
# set flash information
end
答案 1 :(得分:2)
我会建议简单明了的方法:
# in your Comment.rb
validates_inclusion_of :depth, in: 0..2, message: "should be in the range of 0..2"
答案 2 :(得分:1)
您现在得到的错误是因为depth
为零。我相信您想使用self.depth
,例如:
def check_depth
self.depth = 1 if self.depth > 2
end
我不确定发送错误是什么意思...发送错误在哪里?你是一个模特......