@template
是一個對象,在你的情況下nil
。如果這個對象沒有方法(my_helper_method
),你不能調用它(特別是如果它是零)。
幫助程序中定義的方法與常規方法一樣被調用。但不是在控制器中,它們在視圖中被調用。你的helper :all
只是使所有的助手可用的意見。
那麼,在您看來:my_helper_method :arg1, :arg2
如果你需要你的對象(@template
)的方法,你需要給你的對象此方法。
例子:
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
更換
@template
但上面的代碼工作正常在軌2.X – Achaius 2012-01-18 10:26:52但要遷移到Rails3中。我不知道它爲什麼起作用,但幫手應該幫助你的觀點。如果你想在你的控制器中包含助手,請在你的控制器中包含MyControllerHelper。然而,這些仍然是「通常」的方法,而不是對象的實例方法(例如'@ template')。將輔助方法混入模型/實例庫時,可以使它們適用於此對象。但這並不會真正遵循這個慣例。 – pduersteler 2012-01-18 10:29:27
如何使用助手做到這一點? – Achaius 2012-01-18 10:30:17