Rob
Rob

Reputation: 1855

How to render error messages for a json form in Rails

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.

I have format.json { render :json => { :errors => @key.errors.full_messages }, :status => 422 } 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.

category_item_keys controller

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 => { :errors => @key.errors.full_messages }, :status => 422 }
    format.js 
   end
 end

end

def key_params
   params.require(:category_item_key).permit(:name, :key_type)
end

new.html.erb

<%= form_for([@guide, @category, @key], url: guide_category_category_item_keys_path, remote: true, :authenticity_token => true) do |f| %>
   <%= render 'shared/error_messages', object: f.object %>

   <%= f.label :name, "Key name" %>
   <%= f.text_field :name %>

   <%= f.select :key_type, [['Stat', 1], ['Attribute', 2], ['Image', 3], ['Text', 4]] %>

   <%= f.submit "Next"  %>
<% end %>

category_item_key.coffee

# No idea what is needed in here

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.

Upvotes: 2

Views: 4030

Answers (1)

krzysiek
krzysiek

Reputation: 31

category_item_keys controller:

format.json { render :json => @key.errors, :status => 422 }

_save.js.erb

<% if @key.errors.any? %>
  $("<%= j(render 'shared/error_messages') %> ").prependTo('#YoursFormId');
<% else %>
  // do something when no errors
<% end %>

create.js.erb, update.js.erb

<%= render 'save' %>

Upvotes: 3

Related Questions