1

I have a controller which via html shows the user profile, via JSON shows a user hover card w profile info.

class UsersController < ApplicationController

  def show
    @user = User.where(:id => params[:id]).first

    return redirect_to "/" if @user.nil?

    respond_to do |format|
      format.html { render :layout => 'application' }
      format.json { render :json => @user.to_json }
    end
  end
end

The problem is when the user is not found it redirects which works great in via HTML but causes errors with JSON. Is there a clean way to have the redirect only happen if it is a HTML request? What's the right rails, clean way to handle this?

Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

1 Answers1

4

Put the check in the format handler if it's not applicable to all formats. Or have the path you redirect to return something meaningful for a JSON format.

It's somewhat user-hostile to redirect without providing any information regarding why the request failed--this seems a problem better solved by meaningful rendering rather than a redirect for all formats.

(You don't need to specify the application layout, really, it's the default.)

Clarification in response to comment (I think):

The blocks for each format are just that: blocks. They may contain arbitrary code, e.g.:

respond_to do |format|
  format.html { @user.nil? ? redirect_to "/" : render }
  format.json { render :json => @user.to_json }
end

Perhaps not the cleanest, partially because I think it's the wrong way to handle it in the first place.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302