Rails 3:如何在Controller中获取图像路径?

时间:2011-06-29 10:27:08

标签: ruby-on-rails ruby-on-rails-3

要在Controller中获取图像路径,请使用以下方法:

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

有没有更好的方法来找到路径?

6 个答案:

答案 0 :(得分:56)

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

Access Asset Path from Rails Controller

答案 1 :(得分:21)

不确定这是否早在Rails 3中添加,但肯定在Rails 3.1中有效。您现在可以从控制器访问view_context,这样您就可以调用视图通常可以访问的方法:

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

请注意,这将为您提供可公开访问的路径(例如:“/assets/foobar.gif”),而不是本地文件系统路径。

答案 2 :(得分:7)

view_context.image_path('noimage.jpg')

答案 3 :(得分:4)

资产网址:

ActionController::Base.helpers.asset_path(my_path)

图片网址:

ActionController::Base.helpers.image_path(my_path)

答案 4 :(得分:0)

view_context适用于Rails 4.2和Rails 5。

在Rails repo解释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

答案 5 :(得分:-3)

您可能需要查看image_path(image.png)以了解您的方案。

以下是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"