,我越來越未定義「項目」的零級
undefined method `items' for nil:NilClass.
雖然錯誤頁面
我上知道我的購物車在那裏...但是當我打電話給它時,它給我零
車型號
class Cart
attr_reader :items
def self.build_from_hash hash
items = if hash["cart"] then
hash["cart"]["items"].map do |item_data|
CartItem.new item_data["product_id"], item_data["quantity"]
end
else
[]
end
new items
end
def initialize items = []
@items = items
end
def add_item product_id
item = @items.find { |item| item.product_id == product_id }
if item
item.increment
else
@items << CartItem.new(product_id)
end
end
def empty?
@items.empty?
end
def count
@items.length
end
def serialize
items = @items.map do |item|
{
"product_id" => item.product_id,
"quantity" => item.quantity
}
end
{
"items" => items
}
end
def total_price
@items.inject(0) { |sum, item| sum + item.total_price }
end
end
應用控制器
def initialize_cart
@cart = Cart.build_from_hash session
end
車控制
class CartsController < ApplicationController
before_filter :initialize_cart
def add
@cart.add_item params[:id]
session["cart"] = @cart.serialize
product = Product.find params[:id]
redirect_to :back, notice: "Added #{product.name} to cart."
end
def show
end
def checkout
@order_form = OrderForm.new user: User.new
end
end
階控制器
class OrdersController
def create
@order_form = OrderForm.new(
user: User.new(order_params[:user]),
cart: @cart
)
if @order_form.save
redirect_to '/', notice: "Thank you for placing your order."
@cart.empty?
else
render 'carts/checkout'
end
end
查看查看
<div class="container-checkout">
<p class="text-title"> You are checking out the following: </p>
<table class="table table-striped">
<thead class="name-table">
<tr>
<td> Image </td>
<td> Name </td>
<td> Category</td>
<td> Size </td>
<td> Item Price </td>
</tr>
</thead>
<tbody>
<% @cart.items.each do |item| %>
<tr>
<td><img src="<%= item.product.image %>" width="50px"></td>
<td><%= item.product.name.capitalize %></td>
<td><%= item.product.category.name %></td>
<td><%= item.product.size %></td>
<td class="price-item"><%= number_to_currency item.total_price %>
</td>
<% end %>
</tr>
<tr class="total-price total-price-checkout">
<td class="name-table">Total Price</td>
<td class="price-item"><%= number_to_currency @cart.total_price %></td>
</tr>
</tbody>
</table>
</div>
<div class="details-user-form">
<%= form_for @order_form, url: orders_path do |f|%>
<% f.fields_for :user, @order_form.user do |u| %>
<p class="text-title">Fill the form with your details</p>
<p><%= render "orders/errors" %></p>
<p><%= u.text_field :name, placeholder: "Name" %></p>
<p><%= u.text_field :email, placeholder: "Email" %></p>
<p><%= u.text_field :address, placeholder: "Address" %></p>
<p><%= u.text_field :postal_code, placeholder: "Postal code" %></p>
<p><%= u.text_field :city, placeholder: "City" %></p>
<p><%= u.text_field :country, placeholder: "Country" %></p>
<%= f.submit "Place order", class: "order-btn"%><br>
<% end %>
<% end %>
</div>
任何想法,爲什麼它這樣做?也因爲,它之前工作..我不知道它爲什麼停止。
你能不能展示你的整個控制器,特別是'@ cart'變量被設置的部分? – oreoluwa