< mockra >

AJAX with Rails - 30 May 2012


Adding AJAX to a Rails application is pretty easy. There are a couple of simple steps, such as adding remote: true to your form, formatting the response in your controller, and adding an AJAX response file.

Here’s an overview of the changes you’ll need to make to your project.

# View

= form_for [ @project, Note.new ], remote: true do |f|

  = f.text_field :content

  = f.submit

All we need to do with our views, is add the remote: true option to the form. In this example, I’m showing AJAX with nested resources.

# Controller

def create
    @note = @project.notes.build params[:note]
    @note.user_id = current_user.id

    if @note.save
      respond_to do |format|
        format.html { redirect_to @project }
        format.js { render layout: false }
      end
    else
      render :new
    end
end

In the controller we need to add a respond_to block. This will generate the correct response depending on what the client is looking for.

# views/notes/create.js.coffee

$('ul.notes').prepend(
  $("<%=escape_javascript( render 'note',
    note: @note, project: @project )%>")
)

$('.new_note')[0].reset()

$('.best_in_place').best_in_place()

Here’s the response that’s going to load when someone creates a new note in our application. As you can see, we’re adding the note partial to our notes list. We then reset the note form, and reload best_in_place to work with the newly rendered note.