AssetTagHelper::image_path 外部视图
据推测,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
?
Supposedly, ActionController::Base.helpers
acts like a proxy for accessing helpers outside views. However many of the methods defined there rely on controller variables and I'm unable to succesfully call:
ActionController::Base.helpers.image_path("my_image.png")
>> TypeError Exception: can't convert nil into String
Digging at the source I see compute_asset_host
method is trying to access config.asset_host
but config
is nil
.
How can I successfully call image_path
from outside views?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
view_context
访问视图中可用的辅助方法。您可以从控制器中像这样调用
image_path
。Use
view_context
to access those helper methods that are available in the view.You can call
image_path
like this from the controller.对于 Rails 3,请在此处查看更清晰的解决方案 如何我在 Rails 3 控制器中使用 image_path
For Rails 3 please checkout the much cleaner solution here How can I use image_path inside Rails 3 Controller
Mason Jones 发布的此解决方案适合我。
在您的应用程序控制器中:
然后您可以执行以下操作,或执行您需要的任何其他操作。
您正在 ApplicationController 中创建 TagHelper 的 Singelton 实例。无论您需要什么,这都会为您提供帮助。他在帖子中对此进行了解释。
另外,我用它来扩展我的模型(创建一个更灵活的 image_tag 帮助器,如果不存在图像,它会返回默认图像 - 例如 person.small_image 是 person 模型的实例变量,它使用 tag_helper)。为此,我将相同的代码放入扩展 ActiveRecord::Base 的 Monkey Patch 初始值设定项中。然后,我从模型中调用 ActiveRecord::Base.tag_helper 。这有点混乱,但我是 Rails 新手。可能有一种更清洁的方法。
希望有帮助。
This solution, posted by Mason Jones, works for me.
In your application controller:
Then you can do the following kind of thing, or whatever else you need.
You're creating a Singelton instance of TagHelper in your ApplicationController. This gives you the helpers wherever you need them. He explains it in his post.
Also, I use this to extend my models (to create a more flexible image_tag helper that returns a default image if there's no image present -- e.g. person.small_image is an instance variable of the person model, which uses tag_helper). To do that I've put the same code in a Monkey Patch initializer that extends ActiveRecord::Base. I then call ActiveRecord::Base.tag_helper from within my models. This is a bit messy, but I'm new to rails. There's probably a cleaner way.
Hope that helps.