Rails / Ajax /错误处理

So there are tons of articles about how to do this, but certainly there's a best practice...and I don't know enough to filter out silly solutions, good ones, and best ones.

I simply want to submit my forms via ajax (in a dialog) and get the errors back just like I would without using ajax...meaning I like the rails standard error handeling/flash messages/label classes.

  • Is the best way to reload the entire partial?
  • Is the best way to use .js.erb (or coffee) for partial stuff? (If so, can you explain how to use these partials?
  • Is the best way to parse JSON back into the form somehow?

What else am I missing in my [limited] knowledge base?

Using js.erb is the way to go. Here's the rationale:

Reloading part of your page basically defeats the purpose of Ajax - which is to modify the page without having to reload or refresh anything. And parsing JSON would be quite tedious.

Using js.erb lets you easily leverage validations that Rails provides. In your js.erb, you can access anything that you normally would from your controller, including the validation errors, you and you can update DOM elements based on those errors. Since you're modifying individual DOM elements, you don't need to concern yourself over the fact that your form may be inside a partial.

The way I'd do it is to render a create.js.erb view like:

$("#my_dialog").replaceWith("<%= j(render 'dialog') %>");

where _dialog.html.erb contains the HTML for the contents of your dialog.

<div id="my_dialog">
  <!-- flash stuff etc -->
  <%= form_for ... %>
  <!-- ... -->
  <% end %>
</div>

Your controller, for example, will look something like:

class EntriesController < ApplicationController
  def create
    @entry = Entry.new(params[:entry])
    respond_to do |format|
      if @entry.save
        format.html { redirect_to @entry }
        format.js {} # this will render create.js.erb for js requests
      else
        format.html { render action: "new" }
        format.js {} # this will render create.js.erb for js requests
      end
    end
  end
end

summit like 'dat. If you don't want to reload the whole form you can update or do whatever you want in .js.erb