My repo: https://github.com/Gtar69/artstore_hw2 => It's my shopping cart project
Now I want to input a value in the carts/index.html to change cart_item quantity.
No idea how to do that in rails
In typical php it's like
<form action="backend.php">
<td><input type="number" name= "kobe">
<input type="submit" value="submit/>
</td>
However, I want simplify the coding structure instead of using form.
My idea is => view/carts/index.html
<tbody>
<% current_cart.items.each do |product| %>
<tr>
<td><%= render_product_photo(product.default_photo) %></td>
<td>
<%= link_to(product.title, admin_product_path(product)) %>
</td>
<td><%= product.price %></td>
<td>
<input type="number" name= "kobe" value = <%= CartItem.where(product_id: product.id).take!.count%>>
<input type="submit" value="shala">
</td>
<td><%= link_to("改變數量", change_item_quantity_carts_path(:product_id => product.id, :count => 2),
:method => :post , :class => "btn btn-primary btn-lg btn-danger") %></td>
<td><%= link_to("刪除物品", delete_item_carts_path(:product_id => product.id) , :method => :post, :class => "btn btn-primary btn-lg btn-danger") %></td>
</tr>
<% end %>
</tbody>
passing "kobe" variable to carts_controller
def change_item_quantity
product = Product.find(params[:product_id])
# :count => 2
current_cart.change_cart_item_quantity(product ,params[:kobe])
redirect_to carts_path
end
and do backend calculation in model/cart.rb
def change_cart_item_quantity(product, count)
#改變cart_item中的數量
c= CartItem.where(product_id: product.id).take!
c.count = count
c.save
end
I'm still struggling in how to pass "kobe" to controller. Any ideas?
Thanks in advance.
refer to guides.rubyonrails.org/form_helpers.html
I used
<td>
<%= form_tag("/carts/change_item_quantity", method: "post") do%>
<%= label_tag(:q, "改變數量") %>
<%= number_field_tag(:kobe, CartItem.where(product_id: product.id).take!.count)%>
<%= hidden_field_tag(:product_id, product.id)%>
<%= submit_tag("Change") %>
<% end %>
</td>
In that way, I can pass any parameter I needed to controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.