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' }