If you don't mind using jQuery and some ajax'n, I have a blog post that covers this.
Here is some basic information if you want a high level overview.
Add this layout:
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>
This code adds an authentication token to the response. That way, JS can pick it up and send it to the server.
Then we intercept any ajax call in application.js:
function isPost(requestType) { return requestType.toLowerCase() == 'post'; } $(document).ajaxSend(function(event, xhr, settings) { if (isPost(settings.type)) { settings.data = (settings.data ? settings.data + "&" : "") + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN ); } xhr.setRequestHeader("Accept", "text/javascript, application/javascript"); });
Add this to the application controller:
before_filter :correct_safari_and_ie_accept_headers after_filter :set_xhr_flash protected def set_xhr_flash flash.discard if request.xhr? end def correct_safari_and_ie_accept_headers ajax_request_types = ['text/javascript', 'application/json', 'text/xml'] request.accepts.sort!{ |x, y| ajax_request_types.include?(y.to_s) ? 1 : -1 } if request.xhr? end
And in your opinion:
<%= link_to "Delete", delete_product_path(product), :class => 'delete' %>
Back to application.js:
$('a.delete').live('click', function(event) { if(event.button != 0) { return true; } $.post(link.attr('href').substring(0, link.attr('href').indexOf('/delete')), { _method: "delete" }); return false; });
This example performs the deletion, but it is actually the same process for processing messages or tags. The blog has a complete sample application that demonstrates this.
Andy gaskell
source share