简体   繁体   中英

Too may redirects rails respond_to

I have a controller action method that gets all records of establishments from the DB, I then want to share this response with a external entity which is a RhoMobile application, i used respond_to to format the response to JSON.

def index
  @establishments = Establishment.index(params).includes(:assessor)
  @json_establishments = Establishment.all
  respond_to do |format|
    format.html { redirect_to(establishments_url) }
    format.json { render json: @json_establishments.as_json }
  end
end

When i navigate to this action i get an error

net::ERR_TOO_MANY_REDIRECTS

in chrome developer tools on the console tab.

When i remove the { redirect_to(establishments_url) } next to the format.html it's working with a status of 406 (Not Acceptable) but if i would use the search in the action view that i created and click the browsers back button, i get something like:

 ActionController::UnknownFormat in EstablishmentsController#index ActionController::UnknownFormat <div class="source hidden" id="frame-source-0"> <div class="info"> Extracted source (around line <strong>#219</strong>): </div> 

instead and when i refresh the page i get the expected view.

No wonder that it is stuck in redirect loop.

Reason :

establishments_url points to EstablishmentsController#index , and your default format must have been html . So, after setting the variables, it redirects to establishments_url , which again tries to load EstablishmentsController#index .

Solution :

Instead of redirecting to the URL, you need to consider rendering a view (as you did in JSON format).

format.html { render 'establishments/index' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM