2010-11-20 45 views
2

在我的用戶模型我有一個回形針的設置是這樣的:使用Rails環境URL與回形針模型

has_attached_file :profile_pic, 
        :styles => {:large => "300x300>", :medium => "150x150>", :small => "50x50#", :thumb => "30x30#" }, 
        :default_style => :thumb, 
        :default_url => '/images/:attachment/default_:style.png', 

如何使默認網址,包含完整的網址?

http://0.0.0.0:3000/images/:attachment/default_:style.png 
or http://sitename.com/images/:attachment/default_:style.png 

回答

1

In Rails 3在您的模型中添加:include Rails.application.routes.url_helpers

在Rails 2中在您的模型中添加:include ActionController::UrlWriter

然後root_url包含您的應用的基礎網址。那麼你可以這樣做:

has_attached_file :profile_pic, 
        :styles => {:large => "300x300>", :medium => "150x150>", :small => "50x50#", :thumb => "30x30#" }, 
        :default_style => :thumb, 
        :default_url => "#{root_url}/images/:attachment/default_:style.png", 
+0

謝謝,但沒有工作的默認圖片的URL結束了:http://0.0.0.0:3000/images/#{root_url}/images/profile_pics/default_small.png – AnApprentice 2010-11-20 06:03:21

+0

我添加了包括我的模式,並按照指定設置default_url。我需要在某處設置root_url嗎?我無法通過谷歌找到。 – AnApprentice 2010-11-20 06:05:16

+0

你確定你在':default_url'的字符串周圍加了雙引號嗎?否則插值不會發生。 – Alex 2010-11-20 06:09:20

1

root_url不會工作直接。

您需要在使用#{root_url}之前分配Rails.application.routes.default_url_options [:host]。

所以你可以設置配置到你的envs。對於staging.rb/production.rb/development.rb

config.after_initialize do 
    Rails.application.routes.default_url_options[:host] = 'http://localhost:3000' 
    end 
0

最簡單的替代方法:

包括在你的類

include Rails.application.routes.url_helpers 

我的模型爲例得到回形針images絕對地址:

class Post < ActiveRecord::Base 
    include Rails.application.routes.url_helpers 

    validates :image, presence: true 

     has_attached_file :image, styles: { :medium => "640x", thumb: "100x100#" } # # means crop the image 
     validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 

    def image_url 
    relative_path = image.url(:medium) 
    self.add_host_prefix relative_path 
    end 

def thumb_url 
    relative_path = image.url(:thumb) 
    self.add_host_prefix relative_path 
end 

    def add_host_prefix(url) 
    URI.join(root_url, url).to_s 
    end 
end 

和控制器:

class Api::ImagesController < ApplicationController 

    def index 
    @posts = Post.all.order(id: :desc) 
    paginated_records = @posts.paginate(:page => params[:page], :per_page => params[:per_page]) 
    @posts = with_pagination_info(paginated_records) 
    render :json => @posts.to_json({:methods => [:image_url, :thumb_url]}) 
    end 
end 

最後:添加

Rails.application.routes.default_url_options[:host] = 'localhost:3000' 

在:

Your_project_root_deir/config/environments/development.rb

雖然傭工只能在視圖中訪問,但這個工作方案。