How to raise validation errors from Rails Controll

2019-06-09 04:01发布

问题:

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