简体   繁体   English

如何在Rails 3 Controller中使用image_path

[英]How can I use image_path inside Rails 3 Controller

An identical question has been asked before AssetTagHelper::image_path outside views but the solution does not work for Rails 3. AssetTagHelper :: image_path外部视图之前已经询问过相同的问题,但该解决方案不适用于Rails 3。

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. 我有一个要求,我使用JSON格式返回一些数据,部分数据需要返回图像的完整路径。 I am building the response in the controller and calling render :json. 我在控制器中构建响应并调用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. 我还在environment.rb中指定了asset_host,因此我需要一种方法将其包含在Rails控制器内部的返回数据中。

You can use view_context in your controller when doing 'view' tasks like generating links. 在执行“查看”任务(如生成链接)时,可以在控制器中使用view_context The good thing about it is you don't have to include the view helpers in your controller. 关于它的好处是你不必在控制器中包含视图助手。

eg 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_tourl_for的html链接,如果您只想要链接,' only_path '选项设置为false应该为您提供绝对URL。

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM