【发布时间】:2012-09-15 01:21:51
【问题描述】:
是否可以获得回形针附件的绝对 URI?目前,问题是生产环境部署在子 URI 中(Passenger 上:RackBaseURI),但 <paperclip attachment>.url 返回 Rails-app 相对 URI(/system/images/...)。有没有办法获取回形针附件的绝对 URI?
我使用的是 Paperclip v2.7 和 Rails 3.2.8。
【问题讨论】:
是否可以获得回形针附件的绝对 URI?目前,问题是生产环境部署在子 URI 中(Passenger 上:RackBaseURI),但 <paperclip attachment>.url 返回 Rails-app 相对 URI(/system/images/...)。有没有办法获取回形针附件的绝对 URI?
我使用的是 Paperclip v2.7 和 Rails 3.2.8。
【问题讨论】:
asset_url(model.attachment_name.url(:style))
【讨论】:
asset_url不能直接在控制器中使用,但URI.join可以:-)
试试
URI.join(request.url, @model.attachment_name.url)
或
URI(request.url) + @model.attachment_name.url
如果你使用 S3 或绝对 url 是安全的。
更新:这个答案比我的好;)https://stackoverflow.com/a/21027839/683157
【讨论】:
根据这个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
【讨论】:
最广泛适用的方法是首先在相关的配置/环境文件中定义您的资产主机:
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),attach_name = avatar,style = :thumb
<%= image_tag absolute_attachment_url(@person.avatar, :thumb)}" %>
【讨论】:
config.action_controller.asset_host 时不起作用,因为它会给你重复/拧紧的协议 + 主机。
这并不能完全解决原始发布者的问题(它在视图中运行,而不是在模型中运行),但对于试图在视图中“获取回形针附件的绝对 URL”的人可能会有所帮助:那样
image_tag(user.avatar.url(:large))
将图像本身放入您的视图中,
image_url(user.avatar.url(:large))
如果您想直接链接到资产(例如在link_to 调用中),则只返回您需要的 URL。
【讨论】:
您可以添加到您的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。
【讨论】: