在我的用户模型中,我有一个像这样的回形针设置:
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
答案 0 :(得分:1)
在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",
答案 1 :(得分:1)
root_url不会马上工作。
在使用#{root_url}之前,您需要分配Rails.application.routes.default_url_options [:host]。
所以你可以将配置设置为envs。 for staging.rb / production.rb / development.rb
config.after_initialize do
Rails.application.routes.default_url_options[:host] = 'http://localhost:3000'
end
答案 2 :(得分:0)
最简单的替代方法:
包含在你的课程中
include Rails.application.routes.url_helpers
我的模型作为示例获取回形针图像绝对网址:
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
虽然帮助程序只能在视图中访问,但这是有效的解决方案。