[ruby on rails] helper的使用

module ApplicationHelper
  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
end

任意helper中定义的方法在view中可以直接使用,但在controller中使用的话需要在相应的controller中引用

class ApplicationController < ActionController::Base
  include ApplicationHelper
end

除此方法还以在controller中定义helper方法,但在view中使用的话需要
申明helper_method :current_cart

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
      session[:cart_id] = cart.id
    end
    return cart
  end
end

猜你喜欢

转载自blog.csdn.net/qq_41037744/article/details/88703984