3

簡単な計算のためのヘルパーメソッドを作成しました。このヘルパーメソッドは整数を返すだけです。コントローラとビューの両方でヘルパーが必要です。

残念ながら、ビューではうまく機能しますが、コントローラーでは機能しません。undefined local variable or methodエラーが発生します。どうすれば修正できますか?

皆さんありがとう

4

2 に答える 2

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

これで、コントローラーとビューの両方でメソッドcurrent_userを使用できます

于 2010-05-13T10:54:14.163 に答える
4

私は次の解決策を使用します。ヘルパーのメソッドは適切なヘルパーモジュールに保存する必要があると思うからです。

module TestHelper
  def my_helper_method
    #something
  end
end


class SomeController < ApplicationController
  def index
    template.my_helper_method
  end
end
于 2010-05-13T15:12:24.983 に答える