Working through Agile Web Development with Rails – Part 2

This post follows on from Part 1

Iteration B4: Linking To The Cart – Playtime Page 102

The second task to change the image to add_to_cart correctly indicates that you should use a combination of the link_to and image_tag however the solution provided at http://wiki.pragprog.com/cgi-bin/wiki.cgi/PT-B-2
renders a GET request which are not supposed to change anything on the server.

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

The solution should read

<%= link_to image_tag(product.image_url, :border => 0, :alt => “Add to cart”), {:action => :add_to_cart, :id => product}, :method => “post” %>

The key part of this is :method => “post” which renders a JavaScript based form post similar to the line below (note this replaces :post => true which will be deprecated in Rails 2.0).

<a href=”/store/add_to_cart/2″ onclick=”var f = document.createElement(‘form’); f.style.display = ‘none’; this.parentNode.appendChild(f); f.method = ‘POST’; f.action = this.href;var m = document.createElement(‘input’); m.setAttribute(‘type’, ‘hidden’); m.setAttribute(‘name’, ‘_method’); m.setAttribute(‘value’, ‘post’); f.appendChild(m);f.submit();return false;”><img alt=”Add to cart” border=”0″ src=”/images/svn.jpg?1165157156″ /></a>


continued in part 3..

This entry was posted in Random Stuff. Bookmark the permalink.