2011-06-29 139 views

回答

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

Access Asset Path from Rails Controller

+0

這對我不起作用,我想用'image_path'而不是'asset_path'。它無法定位我的圖像文件夾中的文件。改爲使用'view_context'。 –

19

不知道這是否早在Rails 3中加入,但絕對在Rails 3.1中工作。

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

注意,這會給你的公開訪問路徑(例如:「/資產/ foobar的現在,您可以從您的控制器,它允許你打電話是正常訪問到你的觀點方法訪問view_context。 gif「),而不是本地文件系統路徑。

+1

用Rails 3.2 – Dogweather

+1

爲我工作在軌道4,5不工作在軌道4,5 –

+1

爲我工作,包括'asset_url'不加域'的ActionController :: Base.helpers'。 – kolen

5

view_context.image_path('noimage.jpg')

+2

有一點解釋會很好! – gsamaras

+0

 class SomeControllerController < ApplicationController def some_method view_context.image_path('noimage.jpg') end end 

+0

我相信view_context加載asset_path和image_path作爲依賴關係。 – Eddie

-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" 
+0

這在控制器中不起作用。 – davmac

3

資源網址:

ActionController::Base.helpers.asset_path(my_path) 

圖片網址:

0

view_context作品爲我的Rails 4.2和Rails 5

尋找一些代碼在Rails的回購說明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