Topic: Update ActiveRecord using ajax (javascript or coffeescript)

I'm trying to do something in rails that seems pretty common but I'm now seeing how to do it.  I've done searching for the past few weeks with no luck.


The default scaffolding has the new object form and the index form as separate pages.  I want to combine them onto one page and submit using ajax.  Actually I'd prefer to use coffeescript, but I'll settle for either java or coffeescript.

Putting the new form and index on the same view is easy.  I can also capture the form values on submit in coffeescript.  But then what?  The steps seem to be:

1. Submit the values to the server to create a new ActiveRecord instance
2. Get the response
  a. If it's a 200 then get the new ActiveRecord instance back and update the form to show it
  b. If it's not 200 display an appropriate error message


Here's the code I have so far for the views:


list.html.erb

<h1>List Books</h1>

<h3>Add Book</h3>
<%= render 'new_book_form' %>

<h3>My Books</h3>
<%= render 'book_list' %>

<%= link_to 'Back', books_path %>

_new_book_form.html.erb

<%= form_for @book, :remote => true, :html => { 'data-type' => :html } do |f| %>
  <% if @book.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>

      <ul>
      <% @book.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :author %><br />
    <%= f.text_field :author %>
  </div>
  <div class="add-button" id='add-button'>
    <%= f.submit %>
  </div>
<% end %>

_book_list.html.erb

<table id='book-list'>
  <tr>
    <th>Title</th>
    <th>Author</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @all_books.each do |book| %>
  <tr>
    <td><%= book.title %></td>
    <td><%= book.author %></td>
    <td><%= link_to 'Show', book %></td>
    <td><%= link_to 'Edit', edit_book_path(book) %></td>
    <td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>


Any help would be very much appreciated.  Thank you in advance.