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


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

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

           - @category.errors.full_messages.each do |msg| 
             = msg

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


$('.category-list').append("<h4><%= %></h4>");

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


def create
  @category =
    respond_to do |format|
      format.html { }
      format.js { }
    flash[:error] = "Correct the errors as indicated"
    render :new

Source: forms

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.