2012-01-18 16 views
0

私はレール2.xから3.xに移行しました。呼び出し時に今制御方法はコントローラのヘルプ - レール3

undefined method `my_helper_method' for nil:NilClass 

MyController.rb

class MyController < ApplicationController 
    def foo 
     @template.my_helper_method 
    end 
end 

MyControllerHelper.rb

class MyControllerHelper 
    def my_helper_method 
     puts "Hello" 
    end 
end 

ApplicationControllerに

class ApplicationController < ActionController::Base 
    helper :all 
end 
01スロー

これを取得するにはどうすればよいですか?

答えて

1

@templateあなたの場合はnilです。このオブジェクトにメソッド(my_helper_method)が含まれていない場合は、呼び出すことはできません(特にnilではない場合)。

ヘルパーで定義されたメソッドは、通常のメソッドと同様に呼び出されます。しかし、コントローラではなく、ビューで呼び出されます。 helper :allは、すべてのヘルパーをビューで利用できるようにするだけです。

だから、あなたのビューで:あなたがオブジェクト(@template)のための方法が必要な場合my_helper_method :arg1, :arg2

、あなたのオブジェクトにこの方法を提供する必要があります。

例:

class Template < ActiveRecord::Base 

    def my_helper_method 
    # do something on a template instance 
    end 

end 


class MyController < ApplicationController 
    def foo 
    @template = Template.first 
    @template.my_helper_method # which actually isn't a helper 
    end 
end 
ヘルパーは何

module MyHelper def helper_method_for_template(what) end end # in your view helper_method_for_template(@template) 

はヘルパー(ビューのビューヘルパーを混合する際に、あなたのコード内で混乱を持っていることの認識することで混合し、モデル)

class Template < ActiveRecord::Base 
    include MyHelper 

    # Now, there is @template.helper_method_for_template(what) in here. 
    # This can get messy when you are making your helpers available to your 
    # views AND use them here. So why not just write the code in here where it belongs 
    # and leave helpers to the views? 
end 
+0

@templateを置き換えることができます。しかし、上記のコードでは、レール2.xの – Achaius

+0

で正常に動作します。しかし、あなたがrails3に移行しています。私はなぜそれが働いているのかわかりませんが、ヘルパーはあなたの意見を助けることになっています。コントローラにヘルパーを含める場合は、コントローラに 'include MyControllerHelper'を実行してください。しかし、これらは依然として "通常の"メソッドであり、オブジェクトのインスタンスメソッドではありません(例えば '@ template')。ヘルパーメソッドでモデル/インスタンスベースにミキシングするときに、このオブジェクトに対して使用可能にすることができます。しかし、これは本当に条約に従うものではありません。 – pduersteler

+0

ヘルパーを使ってこれを行う方法? – Achaius