控制器引发验证错误

控制器引发验证错误

本文介绍了如何从 Rails 控制器引发验证错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些奇怪的事情.我正在查看 request.env['recaptcha.valid'] 一个特殊的键,我添加到仅对 Rails 控制器可用的请求变量中.

I am dealing with some weird stuff. I am looking at request.env['recaptcha.valid'] a special key I added to the request variable available only to Rails controllers.

根据上述变量的状态,如何从 Rails 控制器引发 Rails 验证错误,而不是在模型中处理此逻辑?

Depending on the state of the above variable, how can I raise a rails validation error from the Rails controller rather than dealing with this logic in the Model?

推荐答案

查看before_filter,可以选择渲染或重定向,或者简单地设置一些内部状态(@captcha_failed = true) 在您的操作被调用之前.

Look into before_filter, which can choose to render or redirect, or simply set some internal state (@captcha_failed = true) before your action is invoked.

你可能想要这样的东西:

You might want something like this:

class MyController < ApplicationController

  before_filter :check_captcha

  # ...

  protected

  def check_captcha
    if params[:captcha] != request.env['recaptcha.valid']
      redirect_to "index", notice: "Invalid captcha"
    end
  end

end

这篇关于如何从 Rails 控制器引发验证错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:46