【问题标题】:how to call a helper method from both view and controller in rails?如何从 Rails 中的视图和控制器调用辅助方法?
【发布时间】:2011-02-19 01:09:12
【问题描述】:

我为一些简单的计算创建了一个辅助方法。这个辅助方法只会返回一个整数。我需要控制器和视图中的助手。

不幸的是,它在视图中运行良好,但在控制器中却不行。我收到undefined local variable or method 错误。我该如何解决?

谢谢大家

【问题讨论】:

    标签: ruby-on-rails model-view-controller helper


    【解决方案1】:

    为了在控制器和视图中使用相同的方法,在 application_controller.rb 中添加你的方法并使其成为辅助方法

    例如

    class ApplicationController < ActionController::Base
      helper :all # include all helpers, all the time
      #protect_from_forgery # See ActionController::RequestForgeryProtection for details
      helper_method :current_user 
    
      def current_user
        session[:user]
      end
    
    end
    

    现在您可以在控制器和视图中使用方法 current_user

    【讨论】:

    • 感谢您的快速响应! :)
    • 关于这个例子的注意事项:由于helper :all 将所有公共方法定义为帮助器,因此不需要helper :allhelper_method :current_user。这是一个非此即彼的命题。
    【解决方案2】:

    我使用以下解决方案。因为我认为 helper 的方法应该存储在适当的 helper 模块中。

    module TestHelper
      def my_helper_method
        #something
      end
    end
    
    
    class SomeController < ApplicationController
      def index
        template.my_helper_method
      end
    end
    

    【讨论】:

    • 我更喜欢这个解决方案而不是选择的那个。但是,与最新的 rails 有细微的变化:所以 stackoverflow.com/questions/3300582/… 你需要使用 view_context 而不是 @template。
    猜你喜欢
    • 2012-02-13
    • 2010-09-14
    • 1970-01-01
    • 2011-08-03
    • 2010-10-02
    • 2011-01-24
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多