0

I've create a partial (views/cart/_cart.html.erb) for my applications shopping cart. I'm rendering it in only in my views/layouts/application.html.erb file. But when I run it I'm getting a NoMethodError on every page other than the views/cart/_cart.index.erb, which I suspect is because it shares the same controller as the partial being rendered.

I've been looking everywhere for an answer & believe it has something to do with how I'm passing variables when rendering the partial, I'll really appreciate it if someone can have a look?

All code can be found here: https://github.com/rossmc/topsnowboards

My code for my partial (views/cart/_cart.html.erb) begins:

<% @cart = cart%>

<h1>Your Cart</h1>

<% if @cart.empty? %>
    <p>There is nothing in your shopping Cart</p>
<% end %>

<% total = 0 %>

<!-- More code displaying the rest of the cart omitted for brevity 

The partial is rendered in views/layouts/application.html.erb with:

<%= render :partial => "/cart/cart", :locals => { :cart => @cart } 

The error message Rails is throwing back at me when I run it is:

NoMethodError in Site#home

Showing Server Side/PROJ-Server Side/app/views/cart/_cart.html.erb where line #5 raised:

undefined method `empty?' for nil:NilClass

Extracted source (around line #5):

2: 
3: <h1>Your Cart</h1>
4: 
5: <% if @cart.empty? %>
6:  <p>There is nothing in your shopping Cart</p>
7: <% end %>
8: 
4

1 回答 1

1

您在此处提到的代码中存在一些冗余。@cart是一个实例变量,它应该可供您的部分使用,而无需将其作为本地传递(当然取决于您首先定义它的位置),因此您不需要购物车部分中的第一行。由于您在应用程序布局中呈现购物车的一部分,因此它将在使用此布局的每个页面(通常是整个站点)中呈现。

您需要使@cart变量可用于站点的每个页面(即每个控制器)。由于每个控制器都继承自您的ApplicationController,因此在此处定义是有意义的@cart。只需将 a 添加before_filterApplicationController定义@cart. 快速浏览您的代码,我说这应该可以解决问题:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :the_cart

  private

  def the_cart
    @cart = session[:cart] || {}
  end

  # the rest of the code ...
end
于 2012-12-02T08:08:47.803 回答