show new data on ajax form submission in rails app

The index view shows all the categories and a form to add a new one. On submitting the form, I’d like the new category to appear in the list. The form submits, the category is saved and I can see in the logs that create.js.erb is rendered. But the new category is not added to the view. Do I need to have the create action in the controller redirect instead to the index view? or how do I get the new category to show in the list

index.haml

%div{class: "col-md-4 col-md-offset-2 category-list"}
- @categories.each do |cat|
  = render 'category', category: cat

%div{class: "col-md-4"}
.btn.btn-success.btn-sm.add-category
  Add a category
.add-category-form
  = form_for [:admin, @category], remote: true, html: {class: "category disabled"} do |f|
    - if @category.errors.any? 
      #error_explanation
        %h2
          = pluralize(@category.errors.count, "error") 
          prohibited this category from being saved:

        %ul
           - @category.errors.full_messages.each do |msg| 
           %li
             = msg

  .category-add
    .form-group
      = f.label :name 
      = f.text_field :name, class: "form-control"
    .form-group
      .controls
        = f.submit '+ Add', class: 'btn btn-success'

create.js.erb

$('.add-category-form').hide();
$('.category-list').append("<h4><%= @category.name %></h4>");

// set form values to blank
$('.add-category-form.input').each(function() {
  $(this).val('');
})

categories_controller.rb

def create
  @category = Category.new(categories_params)
  if @category.save
    respond_to do |format|
      format.html { }
      format.js { }
    end
  else
    flash[:error] = "Correct the errors as indicated"
    render :new
  end
end


Source: forms

Leave a Reply