helper_method

Part A - 概念和规则


规则

  • 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

  1. 在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
  1. 在view里:无法被调用
  • current_cart 这个controller method,被写进下面view里,会报错;即在view里无法使用它
<%= current_cart.products.count %>
  1. 在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
  1. 在view里:能够被调用
  • 经过上面处理后,view里就能调用这个controller method,不会报错
<%= current_cart.products.count %>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容