0

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.

sa77
  • 3,563
  • 3
  • 24
  • 37
Thabo
  • 1,303
  • 2
  • 19
  • 40
  • I am redirecting to establishments_url because i want to go there after i do the search – Thabo Jan 23 '17 at 11:07

1 Answers1

1

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' }
31piy
  • 23,323
  • 6
  • 47
  • 67
  • I still get the ActionController::UnknownFormat text when i click back after the serach – Thabo Jan 23 '17 at 11:07
  • @Teebo can you try appending `.html` in the URL? – 31piy Jan 23 '17 at 11:13
  • Thanks a lot, but there has to be a better way – Thabo Jan 23 '17 at 11:19
  • @Teebo, yes of course there is. See [this post](http://stackoverflow.com/questions/4800219/how-to-set-the-default-format-for-a-route-in-rails) about setting default format of rails routes. – 31piy Jan 23 '17 at 11:37