2013-03-19 18 views
2

我有一个回形针附件的模式:图像Rails的回形针静态文件具有绝对URL

型号:我conttroller的

class HomeScreen < ActiveRecord::Base 
    before_create { !HomeScreen.has_record? } 
    validates :image, :attachment_presence => true 
    attr_accessible :image 
    has_attached_file :image 

    def self.has_record? 
    if HomeScreen.last 
     true 
    else 
     false 
    end 
    end 
end 

显示方法应使用相对路径,但JSON返回图像应返回带域名的绝对网址,我该怎么做?

控制器:

class HomeScreenController < ApplicationController 
    # GET /home_screen 
    def show  
    @home_screen = HomeScreen.last 

    respond_to do |format| 
     format.html 
     format.json { render json: @home_screen } 
    end 
    end 

回答

5

根据github issue,可以执行以下操作:

image_uri = URI.join(request.url, @home_screen.image.url) 

这将是一个URI对象,它可以被转换成一个String.to_s

1

根据相同的github issue,它是清洁剂使用ActionController::Base.asset_host所以它会产生这样的帮手:

def add_host_prefix(url) 
    URI.join(ActionController::Base.asset_host, url) 
    end 

此假设你在每一个/config/environments/<environment>.rb文件中的以下内容:

Appname::Application.configure do 

    # .... 

    config.action_controller.asset_host = 'http://localhost:3000' # Locally 

    # .... 

end