Mis*_*hko 24 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
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来找到路径?
dee*_*our 58
ActionController::Base.helpers.asset_path('missing_file.jpg')
Run Code Online (Sandbox Code Playgroud)
Mat*_*ins 22
不确定这是否早在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
Run Code Online (Sandbox Code Playgroud)
请注意,这将为您提供可公开访问的路径(例如:"/assets/foobar.gif"),而不是本地文件系统路径.
资产网址:
ActionController::Base.helpers.asset_path(my_path)
Run Code Online (Sandbox Code Playgroud)
图片网址:
ActionController::Base.helpers.image_path(my_path)
Run Code Online (Sandbox Code Playgroud)