What causes a 422 Unprocessable Entity Error in Rails 3?

31,598

Solution 1

Turns out that it was this line that was causing this error:

@project = current_user.projects.build(params[:project])

I replaced the build with create and all works now.

Solution 2

The answer here is, that any error in you case will result in '422 Unprocessable Entity' when you're responding in JSON format. The reason is this line in your controller:

format.js   { render :json => @project.errors, :layout => false, :status => :unprocessable_entity }

I.e. when the object has errors and you are responding in JSON format, you will always send the 422 status.

What you actually need is to make a further investigation why would your object have errors. And that could be anything. For example: when not persisting the @project, it may have caused a validation error, etc..

In that case your question is irrelevant and the accepted answer is misleading.

IMHO, you should either change the question, or update the answer.

Share:
31,598

Related videos on Youtube

marcamillion
Author by

marcamillion

Rails developer that loves finance, economics, business & tech.

Updated on October 10, 2020

Comments

  • marcamillion
    marcamillion over 3 years

    This is the error message from the logfile:

    Started POST "/stages" for 127.0.0.1 at 2011-04-02 23:22:18 -0500
    Processing by StagesController#create as JS
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"ob37MMciudHqAnNXFoeofWyVfLnrTxlHfncyDsZLpsI=", "stage"=>{"project_id"=>"3", "name"=>"First"}}
    
      User Load (1.1ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
    #<User id: 1, email: "[email protected]", encrypted_password: "$2a$10$qUbNGm6lZ366jRiE0vK0gOpxbGXD5JmfqWmH1lfLlCEC...", password_salt: "$2a$10$qUbNGm6lZ366jRiE0vK0gO", reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 264, current_sign_in_at: "2011-04-03 04:12:24", last_sign_in_at: "2011-04-03 03:21:37", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", username: "test", f_name: "Test", l_name: "User", created_at: "2011-01-22 07:17:45", updated_at: "2011-04-03 04:12:24", invitation_token: nil, invitation_sent_at: nil, plan_id: 3, current_state: nil, confirmation_token: nil, confirmed_at: "2011-02-11 23:19:15", confirmation_sent_at: "2011-02-11 23:18:20">
    
      Role Load (0.4ms)  SELECT "roles".* FROM "roles" INNER JOIN "assignments" ON "roles".id = "assignments".role_id WHERE (("assignments".user_id = 1))
    Completed 422 Unprocessable Entity in 302ms (Views: 0.2ms | ActiveRecord: 1.5ms)
    

    Any ideas ?

    This is the new & create actions in stage:

    def new
        @project = Project.new
        respond_with(@project)
      end
    
    def create
        #@project = current_user.projects.create(params[:project])
        @project = current_user.projects.build(params[:project])
        #@project.current_user = current_user
        if @project.save
          respond_with(@project, :status => :created, :location => @project) do |format|
            flash.now[:notice] = 'Project was successfully created.'
            format.html { redirect_to(@project) }
            format.js   { render :partial => "projects/show", :locals => {:project => @project}, :layout => false, :status => :created }
          end
        else
          respond_with(@project.errors, :status => :unprocessable_entity) do |format|
              format.js   { render :json => @project.errors, :layout => false, :status => :unprocessable_entity }
              format.html { render :action => "new" }
          end
        end
      end
    

    This is the form partial that creates the new stage:

    <% stage ||= Stage.new 
       new_stage = stage.new_record? %>
    <%= form_for(stage, :html => { :class=>"ajax-form", :id => "stage-ajax-form"}, :remote => true, :disable_with => (new_stage ? "Adding..." : "Saving...")) do |f| %>
        <%= f.hidden_field :project_id %>
        <%#= f.hidden_field :client_id, :value => @project.client.id %>
        <div class="validation-error" style="display:none"></div>
        <label for="stage_name"><span class="icon stage-icon"> </span></label>
        <input type="text" class="name" size="20" name="stage[name]" id="stage_name" value="<%=  stage.name %>" >
    
        <%= f.submit(new_stage ? "Add Stage" : "Save", :class => "green awesome") %>
    <% end %>
    
    • errorhandler
      errorhandler about 13 years
      Could you show some code?, It's really hard to help you just from a log
    • Steve Ross
      Steve Ross about 13 years
      You need to look at the raw post data to figure out why the entity is semantically incorrect. That's request.raw_post.
    • marcamillion
      marcamillion about 13 years
      Steve, I do that in my partial ?
  • Steven Soroka
    Steven Soroka over 9 years
    How would that fix it?
  • sergserg
    sergserg over 9 years
    I have no idea why this fixes the problem. This answer should expand a bit. Build creates the object without persisting it - create persists it so it should still crash,