Last Updated: September 09, 2019
·
748
· bengy

Rails Rendering Format Priorities

I had an issue with one of my Rails projects where JSON was rendering in the response headers of AJAX .get() requests instead of HTML by default.

It was because I was using Rails' scaffolding generator and the slim templating language. I've discovered that Rails prioritises view files based on their extension:

  • .html (or .html.erb)
  • .json (or .json.jbuilder)
  • .* (everything else, including .slim)

Rails was defaulting to rendering .json instead of my .slim file, which is why by default the contents of my AJAX .get() requests were returning "undefined", and browsers were caching JSON versions of my pages instead of HTML versions (replicated when hitting the back button).

This can be solved one of two ways:

First, in your routes file you can specify default format to render.

resources :yourresourcename, defaults: {format: :html}

Second, delete the .json view files generated by Rails scaffolding.

This probably applies .haml files as well, but I haven't tested that assumption.