Javascript – Add events to anchors when using link_to and :method => :post instead of inline Javascript

javascriptjquery-eventsruby-on-rails

I'm jumping into Ruby on Rails with Agile Web Development with Rails.

I got to the part where you use:

<%= link_to (image_tag(product.image_url), {:action => :add_to_cart, :id => product}, :method => :post) %>

In an attempt to be RESTful, Rails kicks out this inline Javascript on each anchor tag

onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'gegcVQGk3yN/q+SjZehByuyAHiqh5BSZWa4QHZb8DOU='); f.appendChild(s);f.submit();return false;"

Now, I'm inclined to never use :method => :post, and instead write some Prototype JS something like:

$$('div.entry a').observe('click', postAnchor);

function postAnchor(event) {
    // create a form around the anchor
    // submit the form with the right product id
}

Is there a way to have my cake and eat it too? Use :method => :post on links, but have Rails kick out a small block of JS like that above?

Or if you use :method => :post, you have to just ignore the gobbledy gook?

Best Solution

There is a piece of that Javascript which makes it difficult to move out. That's this portion right here.

s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'gegcVQGk3yN/q+SjZehByuyAHiqh5BSZWa4QHZb8DOU=');

The authenticity token is used to prevent CSRF attacks. There are work arounds however I prefer to just live with the inline javascript.

That said, Rails 3 will not use inline javascript but instead be unobtrusive. It does this by assigning variables (such as the authenticity token) to HTML 5 tag attributes and parsing it with Javascript.