回答

9

我看到有兩種方式:

  • 在你的Rails服務器的頂部,在生產中有時在開發中,你必須使用Apache或nginx的Web服務器。有了這些,您可以爲其他目錄中的文件提供特定的URL。例如。您可以使http://yourapp.com/images/從特定目錄中提供文件。在軌道,與Nginx的一個traditionnal image_tag

實例顯示圖像:

# Find the right `server` section which you currently use to serve your rails app 
server { 
     listen 80; 

     # Add this 
     location /images { 
     root /var/www/my/specific/folder; 
     } 

     location/{ 
     #... 
     #... Here you should already some code to proxy to your rails server 
     } 
    } 

With that, when you access to `yourserver.com/images`, nginx serve your specific folder and not your rails app. Then in your app view : 

    <%= image_tag 'http://yourserver.com/images/my_pic.jpg' %> 
  • 如果您無法訪問您的服務器設置,你可以從一個控制器動作成爲圖像文件與send_file

    在控制器:

    class ImagesController < ApplicationController 
        def show 
        send_file File.join('/var/www/my/specific/folder',params[:name]), :disposition => 'inline' 
        end 
    end 
    

    config/routes.rb

    match '/images/:name' => 'images#show', :as => :custom_image 
    

    然後,當你訪問這個動作(通過你在config/routes.rb定義的路線),你的形象。所以,在你看來,你做一個traditionnal image_tag這個網址:

    <%= image_tag custom_image_path('my_pic.jpg') %> 
    OR 
    <%= image_tag custom_image_url('my_pic.jpg') %> 
    
+0

看我的編輯。我向你展示瞭如何使用自定義命名路由。 – 2012-02-26 16:08:56

+0

而我剛剛編輯控制器來匹配我的例子... – 2012-02-26 16:11:51

+0

AFAIK,沒有。在導軌範圍內,您必須遵循導軌堆棧。但是在大約30秒內創建一個控制器......如果需要,可以將操作集成到其他控制器中。我寧願推薦您查看第一個解決方案:即使現在在開發中,您的應用程序頂部也沒有Web服務器,但在生產中,您最好花時間學習如何配置它(使apache上的虛擬主機或在nginx中的新服務器...) – 2012-02-26 16:44:46

0

如果它存儲在Rails應用程序目錄外,那麼它不屬於資產管道,你可以簡單地鏈接到它:

<%= image_tag("http://example.com/some_file.jpg") %> 

顯然,這必須要通過HTTP訪問(你需要Nginx的或Apache服務器安裝)。

+0

你在生產中如何使用你的應用程序呢?你是在80端口上運行Mongrel嗎? – 2012-02-26 15:58:20

0

這可能是壞主意,並會導致很多的問題。一些安全性,一些功能,但我實際上不知道的大部分效果。
我知道,從經驗來看,無論什麼時候,違背軌道約定什麼東西是什麼東西,這是一個打滑的東西,最好避免的滑坡。

使用提供的框架創建解決方案。

注意,如果您使用rails 3.1+而不是< = 3.0,則由於將js,css和圖像複製到公共場所的資產編譯,此功能也會受到一些影響。