美文网首页Ruby
helper_method

helper_method

作者: Sarah_友妹 | 来源:发表于2017-10-07 17:05 被阅读3次

    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 %>
    

    相关文章

      网友评论

        本文标题:helper_method

        本文链接:https://www.haomeiwen.com/subject/nuijyxtx.html