Topic: Adding Options To A Cart Item In AWDWR?

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 on 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 it. 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

Re: Adding Options To A Cart Item In AWDWR?

Got a reply on another message board that suggested losing the form helper, and that DOES give me the ability to pass the size parameter on, but I don't know how to associate it with the cart object. how would I add size to an item? Thanks again for anyone that has taken the time to read this.

Re: Adding Options To A Cart Item In AWDWR?

The Solution:

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?).

Re: Adding Options To A Cart Item In AWDWR?

Hi I am attempting to do this with the fourth edition book as it is in Rails 3.1 what would I have to modify to get this to work for my edition?

Last edited by shabankarumba (2012-03-17 14:51:59)