如何从rails中的视图和控制器调用辅助方法?

Vic*_*Lam 3 model-view-controller ruby-on-rails helper

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

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

谢谢大家

Sal*_*lil 10

为了在控制器和视图中使用相同的方法,在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
Run Code Online (Sandbox Code Playgroud)

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