开发者

Rails 3: How to get image path in Controller?

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_fil开发者_Python百科e_name).to_s
    send_file(path, ...)
  end
end

Is there a better method to find the path ?


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

Access Asset Path from Rails Controller


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.


view_context.image_path('noimage.jpg')


Asset url:

ActionController::Base.helpers.asset_path(my_path)

Image url:

ActionController::Base.helpers.image_path(my_path)


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


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜