Rails 3: How to get image path in Controller?

本秂侑毒 提交于 2020-01-22 10:28:07

问题


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 ?


回答1:


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

Access Asset Path from Rails Controller




回答2:


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.




回答3:


view_context.image_path('noimage.jpg')




回答4:


Asset url:

ActionController::Base.helpers.asset_path(my_path)

Image url:

ActionController::Base.helpers.image_path(my_path)



回答5:


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



回答6:


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"


来源:https://stackoverflow.com/questions/6519141/rails-3-how-to-get-image-path-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!