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)
错误..
任何想法为什么?
您的示例失败,因为您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)
添加 helper_method :current_cart到应用程序控制器.
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_cart
...
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12539 次 |
| 最近记录: |