Question about building a basket / box with Rails

advertisements

I just picked up Agile Web Development with Rails 3rd Ed., and I'm going thru the Depot Application chapters, and I have a question about Product/Item options-

If I wanted to modify the product catalog and store so that products could have options (size, color, whatever), where/how would I do that?

Let's say I'm selling t-shirts, and they come in different sizes. I don't feel like that's something that really needs a model created to handle sizes, so I thought I could just add it as a select box in the html in the store's view.

But, each Add to Cart button is wrapped by a form tag that is automatically generated by button_to, and doesn't seem to give me the ability to pass additional parameters to my cart. How can I get the size of the item added into the POST to add_to_cart?

And perhaps more importantly- what is the most Railsy way to do so?

Thanks in advance for any help! --Mark

The helper in my view:

<%= button_to "Add to Cart" , :action => :add_to_cart, :id => product %>

The form that it generates:

<form method="post" action="/store/add_to_cart/3" class="button-to">


Ok, it's 2 days later, and I figured it out. This is what I had to do-

1, in my store view:

<% form_for @product, :url => {:action => "add_to_cart", :id => @product} do |f| %>
  <select name="productsize" id="productsize">
    <option value="L">L</option>
    <option value="XL">XL</option>
  </select>
  <%= f.submit 'Add to Cart' %>
<% end %>

2, added to my store controller:

productsize = params[:productsize]
@cart.add_product(product, productsize)

Had to get productsize from params, and then pass it with the rest of the product model to the cart model's add_product action.

3, adjusted the cart model to accept the argument, and:

@items << CartItem.new(product, productsize)

Passed it along with the rest of the product model to create a new Cart Item and add it to items.

4, added to the cart_item model:

attr_reader :product, :quantity, :productsize

def initialize(product, productsize)
@product = product
@productsize = productsize

to read in productsize and initialize Cart Item.

5, added to my add_to_cart view:

Size: <%=h item.productsize %>

To display it for the user.

That's it. If there is an easier or DRYer way to go about it, I'm all ears (eyes?).