title: How to render error messages for a json form in Rails
body: <p>I'm trying to display error messages for a failed from submit on an ajax form. I haven't gone down the path of ajax forms before and cant find a solid upto date guide on how to get error messages to show when the form fails to save the data for whatever reason.</p>
  
  <p>I have <code>format.json { render :json =&gt; { :errors =&gt; @key.errors.full_messages }, :status =&gt; 422 }</code> in the controller fo a failed form submit as you can see below. But I have no idea on what JS or coffeescript to have so the error messages are displayed. </p>
  
  <p>category_item_keys controller</p>
  
  <pre><code>def new
     @guide      = Guide.friendly.find params[:guide_id]
     @category   = Category.friendly.find params[:category_id]
     @key        = @category.category_item_keys.new
  end
  
  
  def create
  
      @guide      = Guide.friendly.find params[:guide_id]
      @key        = @category.category_item_keys.new key_params
      @category   = Category.friendly.find params[:category_id] 
  
  
   if @key.save
  
      CategoryItemKey.find(@key.id).update(submitted_by: current_user.id, approved_by: current_user.id, guide_id: @guide.id)
  
      respond_to do |format|
  
       format.html {  redirect_to new_guide_category_category_item_key_path(@guide, @category)
                flash[:success] = "Key added successfully!"  }
  
       format.json { render :json }
       format.js 
  
       end
  
   else
      respond_to do |format|
        format.html {  render 'new' }
        format.json { render :json =&gt; { :errors =&gt; @key.errors.full_messages }, :status =&gt; 422 }
      format.js 
     end
   end
  
  end
  
  def key_params
     params.require(:category_item_key).permit(:name, :key_type)
  end
  </code></pre>
  
  <p>new.html.erb</p>
  
  <pre><code>&lt;%= form_for([@guide, @category, @key], url: guide_category_category_item_keys_path, remote: true, :authenticity_token =&gt; true) do |f| %&gt;
     &lt;%= render 'shared/error_messages', object: f.object %&gt;
  
     &lt;%= f.label :name, "Key name" %&gt;
     &lt;%= f.text_field :name %&gt;
  
     &lt;%= f.select :key_type, [['Stat', 1], ['Attribute', 2], ['Image', 3], ['Text', 4]] %&gt;
  
     &lt;%= f.submit "Next"  %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>category_item_key.coffee</p>
  
  <pre><code># No idea what is needed in here
  </code></pre>
  
  <p>I've read over all the posts I can find to see what needs to go in category_item_key.coffee but they are all 3-5 years old and just don't work. I'm sure its not that complicated but I don't know much about JS to get it working.</p>