【问题标题】:Rails 3: How to get image path in Controller?Rails 3:如何在控制器中获取图像路径?
【发布时间】:2011-09-25 00:53:47
【问题描述】:

要在 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

有没有更好的查找路径的方法?

【问题讨论】:

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


【解决方案1】:

不确定这是否早在 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”),而不是本地文件系统路径。

【讨论】:

  • 在 Rails 4 中为我工作
  • 在 Rails 4 中为我工作,包括 asset_url,它不会在 ActionController::Base.helpers 中添加域。
  • 这在没有 view_context 时不起作用。那样的话,更喜欢deefour的方案
【解决方案2】:
ActionController::Base.helpers.asset_path('missing_file.jpg')

Access Asset Path from Rails Controller

【讨论】:

  • 这对我不起作用,我想使用 image_path 而不是 asset_path。它无法定位我的图像文件夹中的文件。使用 view_context 代替。
【解决方案3】:

view_context.image_path('noimage.jpg')

【讨论】:

  • 稍微解释一下就好了!
  •  class SomeControllerController 
  • 我相信 view_context 会加载 assets_path 和 image_path 作为依赖项。
【解决方案4】:

您可能需要查看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"

【讨论】:

    【解决方案5】:

    资产网址:

    ActionController::Base.helpers.asset_path(my_path)
    

    图片网址:

    ActionController::Base.helpers.image_path(my_path)
    

    【讨论】:

      【解决方案6】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-17
        • 2012-03-05
        • 2016-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-30
        相关资源
        最近更新 更多