Part A - 概念和規(guī)則
規(guī)則
- controller里的method,不能在view里使用
問題
- 如果想讓controller里的method侈玄,能夠在view里使用,要怎么做深啤?
解答
- 在controller里將該method,宣告為helper_method
helper_method的定義
- Declare a controller method as a helper, thus this controller method can be used in view.
Part B - 舉例
current_cart
- 在controller里:被定義
- 如下所示路星,它是在ApplicationController里被定義的溯街,它是一個controller method
- 由于它是controller method诱桂,所以它無法在view里使用
class ApplicationController < ActionController::Base
def current_cart
@current_cart || = find_cart
end
private
def find_cart
cart = Cart.find_by(id: session[:cart_id])
if cart.blank?
cart = Cart.create
end
session[:cart_id] = cart.id
return cart
end
- 在view里:無法被調(diào)用
- current_cart 這個controller method,被寫進(jìn)下面view里呈昔,會報錯挥等;即在view里無法使用它
<%= current_cart.products.count %>
- 在controller里:被宣稱為helper_method
- 如果在controller里,宣稱該controller method為helper_method堤尾,如下加上一行 helper_method :current_cart肝劲,則將能夠在view里使用它
class ApplicationController < ActionController::Base
helper_method :current_cart
def current_cart
@current_cart || = find_cart
end
private
def find_cart
cart = Cart.find_by(id: session[:cart_id])
if cart.blank?
cart = Cart.create
end
session[:cart_id] = cart.id
return cart
end
- 在view里:能夠被調(diào)用
- 經(jīng)過上面處理后,view里就能調(diào)用這個controller method郭宝,不會報錯
<%= current_cart.products.count %>