25

An identical question has been asked before AssetTagHelper::image_path outside views but the solution does not work for 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. 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.

Community
  • 1
  • 1
Jhony Fung
  • 2,970
  • 4
  • 29
  • 32

1 Answers1

39

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.

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)

Hope this helps.

David Barlow
  • 4,914
  • 1
  • 28
  • 24
  • For me, I needed to generate a CSS image url to an asset which has a digest in the filename. Thanks to you, Barlow, I came up with this: `"url(#{view_context.asset_path('dir/filename.png')})"` – Matthew Clark Oct 14 '11 at 14:19