Rails 3:如何在Controller中获取图像路径?
要在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
有没有更好的方法来找到路径?
ActionController::Base.helpers.asset_path('missing_file.jpg')
从Rails控制器访问资产路径
不确定这是否早在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”),而不是本地文件系统路径。
view_context.image_path('noimage.jpg')
资产url:
ActionController::Base.helpers.asset_path(my_path)
图片url:
ActionController::Base.helpers.image_path(my_path)
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
您可能想要查看场景的image_path(image.png)
。
以下是文档中的示例:
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"