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

tma*_*ini 5 layout ruby-on-rails ruby-on-rails-3

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

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
Run Code Online (Sandbox Code Playgroud)

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

<div id="cart_menu">
    <ul>
    <li>
      <%= image_tag("cart.jpg")%>
    </li>
    <li>
      <%= link_to "#{current_cart.number_of_items}", current_cart_url %>
    </li>
    <li>
          <a href="/checkout/">Checkout</a>
        </li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

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

undefined local variable or method `current_cart' for #<#<Class:0x2d2d834>:0x2d2b908>
Run Code Online (Sandbox Code Playgroud)

错误..

任何想法为什么?

Adr*_*uio 8

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

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

第一种方法是current_cart在帮助器中移动方法.

第二种方法是@current_cart使用a 设置变量before_filter@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
Run Code Online (Sandbox Code Playgroud)

在你看来:

<%= link_to "#{@current_cart.number_of_items}", current_cart_url %>
Run Code Online (Sandbox Code Playgroud)


Bit*_*rse 7

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

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper_method :current_cart
  ...
end
Run Code Online (Sandbox Code Playgroud)

  • @frank blizzard:`helper:all`意味着你将包含来自_app/helpers_的所有助手的所有方法,这些方法将在视图中提供.但是`helper_method`用于将控制器方法声明为帮助器. (3认同)