Ruby on rails 3 控制器中的助手-Rails 3
我从Rails2.x迁移到了3.x。现在调用控制器方法时抛出 MyController.rbRuby on rails 3 控制器中的助手-Rails 3,ruby-on-rails-3,helpers,controllers,Ruby On Rails 3,Helpers,Controllers,我从Rails2.x迁移到了3.x。现在调用控制器方法时抛出 MyController.rb class MyController < ApplicationController def foo @template.my_helper_method end end 应用控制器 class ApplicationController < ActionController::Base helper :all end class Application
class MyController < ApplicationController
def foo
@template.my_helper_method
end
end
应用控制器
class ApplicationController < ActionController::Base
helper :all
end
class ApplicationController
如何使其工作?
@template
是一个对象,在您的情况下是nil
。如果此对象中没有方法(my\u helper\u method
),则无法调用它(特别是当它为nil时)
在helpers中定义的方法与常规方法一样被调用。但不是在控制器中,而是在视图中调用它们。您的helper:all
只会使所有helper对视图可用
因此,在您看来:my\u helper\u方法: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)
在助手中混合(在将视图助手与视图和模型混合时,请注意代码中存在混乱)
类模板
@template
是一个对象,在您的例子中是nil
。如果此对象中没有方法(my\u helper\u method
),则无法调用它(特别是当它为nil时)
在helpers中定义的方法与常规方法一样被调用。但不是在控制器中,而是在视图中调用它们。您的helper:all
只会使所有helper对视图可用
因此,在您看来:my\u helper\u方法: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)
在助手中混合(在将视图助手与视图和模型混合时,请注意代码中存在混乱)
类模板
另一篇SO帖子实际上回答了这个问题:
基本上,您可以将
@模板
替换为查看上下文
这实际上在另一篇SO帖子中得到了回答:
基本上,您可以将
@模板
替换为查看上下文
,但您正在迁移到rails3。我不知道为什么它会起作用,但是助手应该在你的观点中提供帮助。如果要在控制器中包含帮助程序,请在控制器中包含MyControllerHelper。但是,这些仍然是“常用”方法,而不是对象的实例方法(例如@template
)。在将助手方法混合到模型/实例库中时,可以使它们可用于此对象。但这并不符合惯例。你最好进行迁移
,而不是修补所有东西,这样那些不好的旧东西仍然可以工作
。如果您真的想做第二个,请继续使用Rails2.x。我更新了答案,看看。您想要的是在您的模型中定义这些方法,或者创建任何@template
的方法。但是您正在迁移到rails3。我不知道为什么它会起作用,但是助手应该在你的观点中提供帮助。如果要在控制器中包含帮助程序,请在控制器中包含MyControllerHelper。但是,这些仍然是“常用”方法,而不是对象的实例方法(例如@template
)。在将助手方法混合到模型/实例库中时,可以使它们可用于此对象。但这并不符合惯例。你最好进行迁移
,而不是修补所有东西,这样那些不好的旧东西仍然可以工作
。如果您真的想做第二个,请继续使用Rails2.x。我更新了答案,看看。您想要的是在您的模型中定义这些方法,或者创建@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