剛開始學習導軌。我正在建設我的第一家電子商店。在控制器之前執行視圖?
我有我的頁面products/index
其中列出我的產品。這是視圖(小井):
- @products.each do |product|
br
.ul class='list-group'
li class="list-group-item row"
.textlist class="col-lg-10 col-md-10 col-sm-10 col-xs-9"
.element_products
h4 <b>Category :</b> #{product.category}
.element_products
h4 <b>Description :</b> #{product.content}
.element_products
h4 <b>Price :</b> #{product.price} euros
button class='btn btn-primary btn-right' class="col-lg-1 col-md-1 col-sm-2 col-xs-3"
p <b>Add to Cart</b>
= link_to 'Add', shopping_cart_path(:product_id => product.id), :method => 'POST'
i class="fa fa-cart-plus"
該代碼使用this gem for the shopping cart。我試圖獲得產品/索引中的產品列表,並帶有一個按鈕將項目添加到購物車。
這裏的重要部分是我正在做一個#each在我的產品表(行#1)。 我對產品有一個控制器,如下:
class ProductsController < ApplicationController
def index
@user = User.find(session[:user_id])
@products = Product.all
@product = Product.new
end
[...]
end
這是我的購物車的控制器:
class ShoppingCartsController < ApplicationController
before_filter :extract_shopping_cart
def create
@product_cart = Product.find(@product_id)
@shopping_cart.add(@product_cart, @product_cart.price)
redirect_to shopping_cart_path
end
def show
end
private
def extract_shopping_cart
shopping_cart_id = session[:shopping_cart_id]
@shopping_cart = session[:shopping_cart_id] ?
ShoppingCart.find(shopping_cart_id) : ShoppingCart.create
session[:shopping_cart_id] = @shopping_cart.id
end
end
問題:
在我看來,我用.each
顯示產品表中的所有產品。 要創建新產品,我需要在控制器ShoppingCartsController
第5行中定義@product_cart
(我想添加到購物車的產品)。
現在我將它定義是這樣的:
@product_cart = Product.find(@product_id)
@product_id
應加大在每次執行我.each
循環在視圖的時間,這樣我就可以得到Product.find(1)
,然後Product.find(2)
,然後Product.find(3)
... 但我無法通過@products.each
循環來實現,因爲在視圖中使用了該循環來顯示所有產品。視圖在控制器之後執行。
有什麼辦法來增加@product_id
與.each
環在我的意見,後來就習慣在Products#create
控制器@product_id
?
您需要創建新產品?或product_cart? – Sravan
你能否讓你的問題更清楚,我不明白你想要做什麼 – Lymuel