如何在Rails 3.1中获取资源的绝对URL?

image_path只返回一个path(没有主机)。

url_for helper不会接受一个单独的path,所以像url_for(image_path('image.png'))就不能工作。 虽然ActionDispatch::Http::Url.url_for的内部url_for看起来可以做到这一点( 源代码 ),但似乎并没有公开的接口。

我该怎么去做呢? 最终,像image_url这样的函数可以像url_for那样工作,这样我就可以调用image_url('image.png')并获得所有default_url_options的绝对URL。

 def image_url(source) URI.join(root_url, image_path(source)) end 

这样你可以使用assets_host或者使用assets_hostjoin。

试试这个在你的application_helper.rb (从页面上Spike列出的评论之一):

 def image_url(source) "#{root_url}#{image_path(source)}" end 

我们的生产和分期资产在s3 / cloudfront上,但不在本地/开发。 所以我写了这个(可能是矫枉过正,也许可以简化):

  def get_digest_file(source) return asset_path(source.to_s.downcase) unless Rails.application.config.assets.digests.present? return ActionController::Base.asset_host + "/assets/" + Rails.application.config.assets.digests[source.to_s.downcase] end 

看起来,最近, sass-rails现在以预期的方式解释了scss文件中的image_url命令,parsing为所讨论的图像的最终位置。

从完整的URL在Rails 3中的图像path

 request.protocol + request.host_with_port + image_path('image.png') 

你甚至可以创build一个帮助干这个,就像

 def full_image_path(img_path) request.protocol + request.host_with_port + image_path(img_path) end 

你可以用绝对URL为任何背景图片或其他资源定义CSS。 所以你可以dynamic生成它如下使用sass / scss在你的css文件中获得绝对图像path 。

CSS

 body { background-image: image-url(background.png); } 

在你的环境文件中改变你的

 config.action_controller.asset_host = "http://your.domain.com/" 

那么你的CSS会看起来像这样:

 body { background-image: url(http://your.domain.com/assets/background.png); }