如何在 Rails 3 控制器中使用 image_path [英] How can I use image_path inside Rails 3 Controller

查看:19
本文介绍了如何在 Rails 3 控制器中使用 image_path的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前有人问过一个相同的问题AssetTagHelper::image_path 外部视图但该解决方案不适用于 Rails 3.

An identical question has been asked before AssetTagHelper::image_path outside views but the solution does not work for Rails 3.

我有一个要求,我使用 JSON 格式返回一些数据,而部分数据需要返回图像的完整路径.我正在控制器中构建响应并调用 render :json.我还在 environment.rb 中指定了一个 asset_host,所以我需要一种方法来将它包含在从 Rails 控制器内部返回的数据中.

I have a requirement where I am returning some data using JSON format and part of the data needs to return the full path of the image. I am building the response in the controller and calling render :json. I am also specifying an asset_host in the environment.rb so I need a way to include that in the returned data from inside a Rails controller.

推荐答案

在执行查看"任务(例如生成链接)时,您可以在控制器中使用 view_context.这样做的好处是您不必在控制器中包含视图助手.

You can use view_context in your controller when doing 'view' tasks like generating links. The good thing about it is you don't have to include the view helpers in your controller.

例如在您的控制器中,您可以创建一个变量,该变量将是一个带有 link_tourl_for 的 html 链接(如果您只需要链接,请使用only_path"选项)设置为 false 应该给你绝对网址.

e.g. in your controller you can create a variable which will be a html link with link_to or url_for if you just want the link, 'only_path' option set to false should give you absolute url.

link = view_context.url_for(:action => 'login', :controller => 'members', :only_path => false)

希望这会有所帮助.

这篇关于如何在 Rails 3 控制器中使用 image_path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆