【问题标题】:shared partials error undefined method `empty?' for nil:NilClass共享部分错误未定义方法“空?”对于零:NilClass
【发布时间】:2012-11-19 21:16:39
【问题描述】:

我为我的应用程序购物车创建了一个部分 (views/cart/_cart.html.erb)。我只在我的 views/layouts/application.html.erb 文件中呈现它。但是当我运行它时,除了 views/cart/_cart.index.erb 之外的每个页面上都会出现 NoMethodError,我怀疑这是因为它与正在渲染的部分共享相同的控制器。

我一直在到处寻找答案,并相信这与我在渲染部分时传递变量的方式有关,如果有人可以看看,我将不胜感激?

所有代码都可以在这里找到:https://github.com/rossmc/topsnowboards

我的部分代码 (views/cart/_cart.html.erb) 开始:

<% @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 

部分在 views/layouts/application.html.erb 中呈现:

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

错误消息当我运行 Rails 时,它向我抛出:

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: 

【问题讨论】:

    标签: ruby-on-rails model-view-controller local-variables renderpartial partials


    【解决方案1】:

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

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

    # 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
    

    【讨论】:

    • 这适用于部分但当我尝试使用 Devise 登录时会引发另一个错误。错误是:没有路由匹配 {:controller=>"devise/products"}。我正在通过以下方式链接到 application.html.erb 中的登录页面:
    • 我尝试将 link_to 更改为: "/products", new_user_session_path %>。但我得到更多错误
    • 我想这应该进入一个单独的问题,因为主要问题已经得到解答,新问题似乎与这个问题无关。请不要忘记在新问题中添加控制台转储。
    • 感谢艾哈迈德,非常感谢您的帮助。我在这里发布了我的新问题stackoverflow.com/q/13674840/1814446
    • 你说得对,艾哈迈德,这是一个单独的问题。我没有在部分中正确定义 link_to 以使用设计。再次感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多