从布局视图调用辅助方法时,rails“undefined method”

我有一个帮助方法来获取我的应用程序控制器中的当前购物车:

class ApplicationController < ActionController::Base protect_from_forgery helper :all # include all helpers, all the time private def current_cart if session[:cart_id] @current_cart ||= Cart.find(session[:cart_id]) session[:cart_id] = nil if @current_cart.purchased_at end if session[:cart_id].nil? @current_cart = Cart.create! session[:cart_id] = @current_cart.id end @current_cart end end 

我可以从大多数视图中调用该方法,但我想在views / layout / application.html.erb文件中使用它,如下所示:

  

但是当我尝试的时候,我得到了一个

 undefined local variable or method `current_cart' for #<#:0x2d2b908> 

错误..

任何想法为什么?

helper_method :current_cart添加到应用程序控制器。

 class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_cart ... end 

您的示例失败,因为您在ApplicationController中定义方法current_cart但在视图中无法访问控制器方法。

有两种方法可以达到你想要的效果:

第一种方法是将方法current_cart移动到帮助器中。

第二种方法是使用before_filter设置变量@current_cart并在视图中使用@current_cart ,如下所示:

 class ApplicationController < ActionController::Base protect_from_forgery helper :all # include all helpers, all the time before_filter :set_current_cart private def set_current_cart if session[:cart_id] @current_cart ||= Cart.find(session[:cart_id]) session[:cart_id] = nil if @current_cart.purchased_at end if session[:cart_id].nil? @current_cart = Cart.create! session[:cart_id] = @current_cart.id end end end 

在你看来:

 <%= link_to "#{@current_cart.number_of_items}", current_cart_url %> 

辅助方法属于辅助模块,例如在app/helpers/application_helper.rb

我实际上不确定,为什么这在其他视图中有效,但我认为,作为站点范围的逻辑,您应该将其定义为ApplicationController的before_filter。 如果您只需要在一个控制器中,请将其放在那里。

而且它不是“帮助者”。 助手存储在app/helpers ,通常用于通过在其方法中隐藏一些html来简化视图。