Rails3 - How To Render 403 in before_filter w/o DoubleRender Error

Bryan Marble picture Bryan Marble · Nov 10, 2011 · Viewed 7.6k times · Source

I have a before_filter that checks the validity of an API key. If the key is invalid, I'd like to render a header-only 403 response.

In my controller:

before_filter :validate_api
...
def validate_api
  if params[:api_key].present? and ApiKey.find(params[:api_key])
    return true
  else
    render head :forbidden
  end
end

The problem is that I get a DoubleRender error, presumably when Rails goes into the action and attempts to render the response anyways. It was my understanding that Rails prevents execution of the action if a before_filter renders or redirects. Is that not the case?

How do I render a header-only response in a before_filter and prevent actions from being executed?

Answer

Kris picture Kris · Nov 10, 2011

Have you tried returning false in the else part?