控制器如何为某个字段手动设置验证错误 [英] how can a controller manually set validation errors for a certain field

查看:41
本文介绍了控制器如何为某个字段手动设置验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 个 ActiveRecord 字段的表单.其中一个字段有一些愚蠢的和状态相关的验证要求.(例如,如果对象是在设置向导表单上创建的,我只会验证该字段.)

I have a form with 3 ActiveRecord fields. One of those fields has kind of goofy, and STATE-DEPENDENT validation requirements. (For example, I only validate the field if the object is being created on a setup wizard form.)

在我创建对象的POST处理程序中,我想我可以调用errors.add来插入一个特殊的错误条件

In my POST handler to create the object, I thought I could call errors.add to insert a special error condition

@foo = Foo.new(params[:foo])
if goofy_conditions(params[:foo][:goofy_field])
  @foo.errors.add(:goofy_field, "doesn't meet the goofy conditions" )
end
respond_to do |format|
  if @foo.save
    ...
  else
    ... redirect back to form (with error fields hilited)

但是,在控制器中执行 @foo.errors.add() 似乎没有任何作用……如果其他字段通过验证,它不会阻止 save().

However, doing @foo.errors.add() in the controller doesn't seem to do anything... it doesnt prevent the save() if the other fields pass validations.

另一种方法是将自定义验证处理程序放入模型中...我知道使用 errors.add(:field, 'msg') 在那里工作正常...但在这种情况下,我的控制器如何传递"信息给验证器,告诉它该字段是否需要验证.

An alternative is to put a custom validation handler into the model... I know using errors.add(:field, 'msg') works fine there... but in that case how can my controller 'pass' info to the validator telling it whether or not the field needs to be validated.

推荐答案

那就是模型逻辑.查看自定义验证

class GoofyThing < ActiveRecord::Base
  validate :goofy_attribute_is_goofy

  def goofy_attribute_is_goofy
    if goofy_conditions(self.goofy_field)
      self.errors.add(:goofy_field, "doesn't meet the goofy conditions" )
    end
  end
end

然后它会像任何其他验证一样工作.

Then it'll act just like any other validation.

编辑

您可以使用 :if 选项有条件地验证:

You can conditionally validate with the :if option:

attr_accessible :via_wizard
validate :goofy_attribute_is_goofy, :if => lambda { self.via_wizard }

并在您的控制器中:

class WizardController < ApplicationController
  before_filter :get_object, :set_wizard

  #...

  def get_object
    @object = GoofyThing.find(params[:id])
  end

  def set_wizard
    @object.via_wizard = true
  end
end

这篇关于控制器如何为某个字段手动设置验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆