Rails的“未定义方法"从布局视图调用辅助方法时 [英] rails "undefined method" when invoking a helper method from layout view
本文介绍了Rails的“未定义方法"从布局视图调用辅助方法时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个帮助器方法可以在我的应用程序控制器中获取当前购物车:
I have an helper method in to get the current shopping cart in my application controller:
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文件中使用该方法, 像这样:
I can call the method from most of my views, but I want to use it in the views/layout/application.html.erb file, like this:
<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>
但是当我尝试这样做时,我会得到一个
But when I try that, I get an
undefined local variable or method `current_cart' for #<#<Class:0x2d2d834>:0x2d2b908>
错误..
有什么想法吗?
推荐答案
将helper_method :current_cart
添加到您的应用程序控制器中.
Add helper_method :current_cart
to your application controller.
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_cart
...
end
这篇关于Rails的“未定义方法"从布局视图调用辅助方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文