Question about creating a shopping cart / checkout with Rails

I just picked up Agile Web Development with Rails 3rd Ed. And I go through the Depot app chapters and I have a question about product / item options -

If I wanted to change the product catalog and save it so that the products could have parameters (size, color, whatever), where / how could I do this?

Say I sell T-shirts, and they come in different sizes. I don’t like the fact that it really needs a model created for handling sizes, so I thought that I could just add it as a selection window in html in the store view.

But each "Add to Cart" button is wrapped with a form tag that is automatically generated by button_to and does not seem to allow me to pass additional parameters to my cart. How can I get the size of an element added in POST in add_to_cart?

And, perhaps more importantly , what is the most Railsy way to do this?

Thanks in advance for your help! --Mark

The assistant in my opinion:

<%= 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">

+3
source share
4 answers

Well, this is after 2 days, and I figured it out. This is what I had to do -

1, in my store:

<% 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 the store controller:

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

If you would get products from params, then transfer it with the rest of the product model to the add_product action of the cart model.

3, , , :

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

, Cart .

4, cart_item:

attr_reader :product, :quantity, :productsize

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

productize Cart.

5, add_to_cart:

Size: <%=h item.productsize %>

.

. DRYER, (?).

+4

, , , cart_item, , . - :

<% form_for(@cart_item) do |f| %>
<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>
<%= f.hidden_field :product_id, :value => @product.id %> 
# other properties...
<%= f.submit 'Add to Cart' %>
<% end %>
+1

button_to , add_to_cart.

<% form_for(@product) do |f| %>
<%= f.select :size, ['S', 'M', 'L', 'XL', 'XXL'] %>
# other properties...
<%= f.submit 'Add to Cart' %>
<% end %>
0

You will need to add attributes to your model. To do this, you need to create a migration to update the database table. I have only the second edition of the book, but there is a section, “Iteration A2: Add a Missing Column”, which describes how to do this. I assume that a similar section will be in the third edition.

You can then follow the Can Berk Güder offer and replace the button with a form.

0
source

Source: https://habr.com/ru/post/1699333/


All Articles