How to raise validation errors from Rails Controller?

夙愿已清 提交于 2020-01-03 06:04:45

问题


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.

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?


回答1:


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


来源:https://stackoverflow.com/questions/17476227/how-to-raise-validation-errors-from-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!