28

To get the image path in Controller I use the following method:

class AssetsController < ApplicationController
  def download(image_file_name)
    path = Rails.root.join("public", "images", image_file_name).to_s
    send_file(path, ...)
  end
end

Is there a better method to find the path ?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • Possible duplicate of [Access Asset Path from Rails Controller](https://stackoverflow.com/questions/7827078/access-asset-path-from-rails-controller) – vinibrsl Dec 06 '18 at 20:01

6 Answers6

65
ActionController::Base.helpers.asset_path('missing_file.jpg')

Access Asset Path from Rails Controller

Community
  • 1
  • 1
deefour
  • 34,974
  • 7
  • 97
  • 90
  • 1
    This did not work for me, I wanted to use `image_path` not `asset_path`. It could not target files in my images folder. Using `view_context` worked instead. – Seth Jeffery Oct 12 '15 at 07:58
  • For anybody using webpacker to handle static assets use this instead: `ActionController::Base.helpers.asset_pack_path('missing_file.jpg')`. – stratis Apr 04 '22 at 11:45
24

Not sure if this was added as early as Rails 3, but is definitely working in Rails 3.1. You can now access the view_context from your controller, which allows you to call methods that are normally accessible to your views:

class AssetsController < ApplicationController
  def download(image_file_name)
    path = view_context.image_path(image_file_name)
    # ... use path here ...
  end
end

Note that this will give you the publicly accessible path (e.g.: "/assets/foobar.gif"), not the local filesystem path.

Matt Huggins
  • 81,398
  • 36
  • 149
  • 218
8

view_context.image_path('noimage.jpg')

Ricardo Rivas
  • 620
  • 6
  • 8
6

Asset url:

ActionController::Base.helpers.asset_path(my_path)

Image url:

ActionController::Base.helpers.image_path(my_path)
ilgam
  • 4,092
  • 1
  • 35
  • 28
0

view_context works for me in Rails 4.2 and Rails 5.

Find some codes in Rails repo explains view_context:

# definition
module ActionView
  # ...
  module Rendering
    # ...
    def view_context
      view_context_class.new(view_renderer, view_assigns, self)
    end
  end
end

# called in controller module
module ActionController
  # ...
  module Helpers
    # Provides a proxy to access helper methods from outside the view.
    def helpers
      @_helper_proxy ||= view_context
    end
  end
end
Devin
  • 139
  • 1
  • 7
-3

You might want to check out image_path(image.png) for your scenario.

Here are the examples from the docs:

image_path("edit")                                 # => "/images/edit"
image_path("edit.png")                             # => "/images/edit.png"
image_path("icons/edit.png")                       # => "/images/icons/edit.png"
image_path("/icons/edit.png")                      # => "/icons/edit.png"
image_path("http://www.example.com/img/edit.png")  # => "http://www.example.com/img/edit.png"
Marius Butuc
  • 17,781
  • 22
  • 77
  • 111