rornoob.com >

Where is :unprocessable_entity ?


23-Jul-2009

I've been working on some existing code that handles RESTful authentication. The users controller contains a section of code like the following to check the login credentials against a valid user.

  def login
  
    @user = User.login(params[:user][:user_name], params[:user][:password])
	
    respond_to do |format|
      if @user
        format.html  { render :action=>:show }
        format.json  { render :json => @user, :status => :ok, :location => @user }
      else
        @users = []
        format.html  { render :action => "index" }
        format.json  { render :json => 'access denied', :status => :unprocessable_entity }
      end
  end

I noticed that the code returns :status => :unprocessable_entity if the login fails. That sounds reasonable, but what actually is that status code, and what other status codes are available should I wish to return different results depending on whether say, the user_name is invalid, or the database is unavailable?

A search for :unprocessable_entity on google and bing didn't really help - there were examples of code using that symbol but nothing that jumped out as explaining what the symbol refers and what the alternative values for :status are.

Is it just one of those rails things where everyone uses something that magically works? Or am I the only one that doesn't know what :unprocessable_entity stands for?

Eventually I came across a post by Cody Fauser, Rails HTTP Status Code to Symbol Mapping which sounded like it might provide an answer to my question, and indeed it did!

It looks like Cody started off with the same problem as me, "...searching through Rails didn't yield any results for a symbol like :unprocessable_entity...", but he went ahead and figured out the answer.

The key is this: The ruby symbol used is an underscored version of the HTTP status message with no spaces

Now it all makes sense! A search on google for http status "Unprocessable Entity" or http status 422 gives many more results than a search for rails :unprocessable_entity. Now I know what that :status symbol means and what all its valid values are.

So I can add in extra checks (catch exceptions?) and return other suitable status values like :unauthorized :request_timeout and :internal_server_error depending on the exact situation.

|

del.icio.usDiggblogmarksNewsvineStumbleUponTechnoratiFurlReddit

Add your comment
Name
Website
Heading
Comment