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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)