Note that there are some explanatory texts on larger screens.

plurals
  1. POrails convention for http raising errors in controllers?
    text
    copied!<p>lets say I have an articles_controller with a show method</p> <p>I want to make sure that only clients with a valid license code can read the json endpoint for this controller action</p> <pre><code>def show authenticate_license if params[:format] == 'json' # boilerplate respond_to do |format| format.html format.json { render json: @article, status: :ok } end end </code></pre> <p>I might want to use this authentication block somewhere else, so i put it into my application_controller</p> <pre><code># in application_controller def authenticate_license @client = params[:client] licenses = License.where(:code =&gt; params[:code]) @license = licenses.first if @license if @license.client = @client # do nothing, we're fine else respond_to do |format| format.json { render json: 'wrong client', status: 400 } end end else respond_to do |format| format.json { render json: 'bad license', status: :forbidden } end end end </code></pre> <p>but this results in a doublerendererror so now i'll try something different</p> <pre><code># in application_controller def authenticate_license licenses = License.where(:code =&gt; params[:code] @license = licenses.first if @license if @license.client = @client # do nothing, we're fine else raise ActionController::RoutingError.new('wrong client') end else raise ActionController::RoutingError.new('bad license code') end end rescue_from ActionController::RoutingError do |exception| respond_to do |format| format.html { redirect_to root_url, :alert =&gt; exception.message } format.json { render json: exception.message, status: :forbidden } end end </code></pre> <p>but this way, I can't specify the HTTP status, and I'm also catching routing errors I probably don't want to catch.</p> <p>What's the correct way to do what I want to do?</p> <p>The behavior I'm describing is sort of what devise does. If you make a request to an action that has the authorize_user! method for example, it will raise an error, and redirect the user to some page. CanCan does something similar too, if a user is not authorized to do something, it raises it's own exception that you're supposed to catch.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload