据推测,ActionController::Base.helpers
就像访问视图之外的助手一样。然而,那里定义的许多方法依赖于控制器变量,我无法成功调用:
ActionController::Base.helpers.image_path("my_image.png")
>> TypeError Exception: can't convert nil into String
从源头上挖掘我看到compute_asset_host
方法正在尝试访问config.asset_host
,但config
为nil
。
如何从外部视图成功呼叫image_path
?
答案 0 :(得分:12)
使用view_context
访问视图中可用的辅助方法。
您可以从控制器中调用此image_path
。
view_context.image_path "my_image.png"
答案 1 :(得分:5)
对于Rails 3,请在此处查看更清晰的解决方案How can I use image_path inside Rails 3 Controller
答案 2 :(得分:0)
This solution为我工作。
在您的应用程序控制器中:
def self.tag_helper
TagHelper.instance
end
class TagHelper
include Singleton
include ActionView::Helpers::TagHelper
include ActionView::Helpers::AssetTagHelper
end
然后你可以做以下的事情,或者你需要的任何事情。
active_scaffold :mything do |config|
config.columns = [:name, :number, :active, :description]
config.update.link.label = tag_helper.image_tag('document_edit.png', :width => "30")
config.delete.link.label = tag_helper.image_tag('document_delete.png', :width => "30")
config.show.link.label = tag_helper.image_tag('document.png', :width => "30")
list.sorting = {:name => 'ASC'}
end
您正在ApplicationController中创建TagHelper的Singelton实例。无论何时需要帮助,都可以为您提供帮助。他在帖子中解释了这一点。
另外,我使用它来扩展我的模型(创建一个更灵活的image_tag帮助器,如果没有图像存在则返回默认图像 - 例如person.small_image是人模型的实例变量,它使用tag_helper)。为此,我将相同的代码放在扩展ActiveRecord :: Base的Monkey Patch初始化程序中。然后我从我的模型中调用ActiveRecord :: Base.tag_helper。这有点乱,但我是铁杆新手。可能有一种更清洁的方式。
希望有所帮助。