Read more

Rails 3: Make "link_to :remote => true" replace HTML elements with jQuery

Tobias Kraze
July 20, 2011Software engineer at makandra GmbH

In Rails 2, you could use link_to_remote ... :update => 'id' to automatically replace the content of $('#id').

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

To do the same in Rails 3, include usual rails-ujs JavaScript Show archive.org snapshot , and put this into your application.js:

$(function() {
  $('[data-remote][data-replace]')
    .data('type', 'html')
    .live('ajax:success', function(event, data) {
      var $this = $(this);
      $($this.data('replace')).html(data);
      $this.trigger('ajax:replaced');
    });
});

Use with

link_to 'Do something', path_returning_partial, :remote => true, :"data-replace" => '#some_id'

If you need to do something after replacing, you can listen to the ajax:replaced event on the link.

.unobtrusive version

In case you are using our unobtrusive JavaScript helper, use the following code instead:

$.unobtrusive(function() {
  $('[data-remote][data-replace]')
    .data('type', 'html')
    .live('ajax:success', function(event, data) {
      var $this = $(this);
      $($this.data('replace'))
        .html(data)
        .activateUnobtrusiveJavascript();
      $this.trigger('ajax:replaced');
    });
});
Posted by Tobias Kraze to makandra dev (2011-07-20 17:07)