簡単な計算のためのヘルパーメソッドを作成しました。このヘルパーメソッドは整数を返すだけです。コントローラとビューの両方でヘルパーが必要です。
残念ながら、ビューではうまく機能しますが、コントローラーでは機能しません。undefined local variable or method
エラーが発生します。どうすれば修正できますか?
皆さんありがとう
簡単な計算のためのヘルパーメソッドを作成しました。このヘルパーメソッドは整数を返すだけです。コントローラとビューの両方でヘルパーが必要です。
残念ながら、ビューではうまく機能しますが、コントローラーでは機能しません。undefined local variable or method
エラーが発生します。どうすれば修正できますか?
皆さんありがとう
コントローラとビューの両方で同じメソッドを使用するには、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を使用できます
私は次の解決策を使用します。ヘルパーのメソッドは適切なヘルパーモジュールに保存する必要があると思うからです。
module TestHelper
def my_helper_method
#something
end
end
class SomeController < ApplicationController
def index
template.my_helper_method
end
end