views:

337

answers:

1

So 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 to? 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 garbledy gook?

+1  A: 

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.

ryanb
Cool, I can just use form_authenticity_token.inspect in my postAnchor function. Interested to see the next iteration of this.
rpflo