获取回形针附件的绝对URL

是否可以获取Paperclip附件的绝对URI? 现在,问题是生产环境部署在子URI中(在Passenger: RackBaseURI ),但.url RackBaseURI .url返回Rails-app相对URI( /system/images/... )。 有没有办法获得Paperclip附件的绝对URI?

我正在使用Paperclip v2.7和Rails 3.2.8。

尝试

 URI.join(request.url, @model.attachment_name.url) 

要么

 URI(request.url) + @model.attachment_name.url 

如果您使用S3或绝对url,这是安全的。

更新:这个答案比我的好;) https://stackoverflow.com/a/21027839/683157

 asset_url(model.attachment_name.url(:style)) 

相关的github问题

根据这个github问题 ,使用ActionController::Base.asset_host更清晰,因此它会产生帮助:

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

这假设您在每个/config/environments/.rb文件中都有以下内容:

 Appname::Application.configure do # .... config.action_controller.asset_host = 'http://localhost:3000' # Locally # .... end 

最广泛适用的方法是首先在相关的配置/环境文件中定义资产主机:

 config.action_controller.asset_host = "http://assethost.com" config.action_mailer.asset_host = "http://assethost.com" 

然后在视图和邮件中:

 asset_url(model.attachment.url(:style)) 

在控制台中:

 helper.asset_url(model.attachment.url(:style)) 

在模型中:

 ApplicationController.helpers.asset_url(model.attachment.url(:style)) 

你可以这样做:

 <%= image_tag "#{request.protocol}#{request.host_with_port}#{@model.attachment_name.url(:attachment_style)}" %> 

或者使用辅助方法来包装它。

 def absolute_attachment_url(attachment_name, attachment_style = :original) "#{request.protocol}#{request.host_with_port}#{attachment_name.url(attachment_style)}" end 

并像这样使用它:

 <%= image_tag absolute_attachment_url(attachment_name, :attachment_style)}" %> 

例如:Model = Person(@person),attachment_name = avatar,style =:thumb

 <%= image_tag absolute_attachment_url(@person.avatar, :thumb)}" %> 

这并不能完全解决原始海报的问题(它在视图中运行,而不是在模型中运行),但对于那些试图在其视图中“获取回形针附件的绝对URL”的人可能会有所帮助:以同样的方式

 image_tag(user.avatar.url(:large)) 

将图像本身放入您的视图中

 image_url(user.avatar.url(:large)) 

如果您想直接链接到资产, link_to返回您需要的URL(例如,在link_to调用中)。

您可以添加到application.rb (或config/environments/*特定环境):

 config.paperclip_defaults = { url: "http://my.address.com/system/:class/:attachment/:id_partition/:style.:extension", path: ':rails_root/public/system/:class/:attachment/:id_partition/:style.:extension', } 

重新启动并重新导入图像。

PS:显然你可以用环境变量替换http://my.address.com 。