ber*_*kes 37 ruby url ruby-on-rails path ruby-on-rails-3
我有一个包含载波上传的图片:
Image.find(:first).image.url #=> "/uploads/image/4d90/display_foo.jpg"
Run Code Online (Sandbox Code Playgroud)
在我看来,我想找到这个绝对的网址.追加root_url会导致双倍/.
root_url + image.url #=> http://localhost:3000//uploads/image/4d90/display_foo.jpg
Run Code Online (Sandbox Code Playgroud)
我不能使用url_for(我知道的),因为这要么允许传递的路径,或者选项标识资源和列表:only_path选项.由于我没有可通过"controller"+"action"识别的资源,因此我无法使用该:only_path选项.
url_for(image.url, :only_path => true) #=> wrong amount of parameters, 2 for 1
Run Code Online (Sandbox Code Playgroud)
在Rails3中创建一个完整URL的路径最干净,最好的方法是什么?
nch*_*rro 98
您也可以asset_host像这样设置CarrierWave的配置设置:
# config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.storage = :file
config.asset_host = ActionController::Base.asset_host
end
Run Code Online (Sandbox Code Playgroud)
这^告诉CarrierWave使用您的应用程序config.action_controller.asset_host设置,该设置可以在您的某个config/envrionments/[environment].rb文件中定义. 有关详细信息,请参见此处
或明确设置:
config.asset_host = 'http://example.com'
Run Code Online (Sandbox Code Playgroud)
重新启动你的应用程序,你很高兴 - 不需要帮助方法.
*我正在使用Rails 3.2和CarrierWave 0.7.1
fl0*_*00r 33
尝试path方法
Image.find(:first).image.path
Run Code Online (Sandbox Code Playgroud)
UPD
request.host + Image.find(:first).image.url
Run Code Online (Sandbox Code Playgroud)
并且你可以把它作为帮助包装它来永远地干它
request.protocol + request.host_with_port + Image.find(:first).image.url
Run Code Online (Sandbox Code Playgroud)
c2h*_*2h2 11
另一个使用的简单方法是URI.parse,在你的情况下是
require 'uri'
(URI.parse(root_url) + image.url).to_s
Run Code Online (Sandbox Code Playgroud)
和一些例子:
1.9.2p320 :001 > require 'uri'
=> true
1.9.2p320 :002 > a = "http://asdf.com/hello"
=> "http://asdf.com/hello"
1.9.2p320 :003 > b = "/world/hello"
=> "/world/hello"
1.9.2p320 :004 > c = "world"
=> "world"
1.9.2p320 :005 > d = "http://asdf.com/ccc/bbb"
=> "http://asdf.com/ccc/bbb"
1.9.2p320 :006 > e = "http://newurl.com"
=> "http://newurl.com"
1.9.2p320 :007 > (URI.parse(a)+b).to_s
=> "http://asdf.com/world/hello"
1.9.2p320 :008 > (URI.parse(a)+c).to_s
=> "http://asdf.com/world"
1.9.2p320 :009 > (URI.parse(a)+d).to_s
=> "http://asdf.com/ccc/bbb"
1.9.2p320 :010 > (URI.parse(a)+e).to_s
=> "http://newurl.com"
Run Code Online (Sandbox Code Playgroud)
只需采取答案并提供帮助:
# Use with the same arguments as image_tag. Returns the same, except including
# a full path in the src URL. Useful for templates that will be rendered into
# emails etc.
def absolute_image_tag(*args)
raw(image_tag(*args).sub /src="(.*?)"/, "src=\"#{request.protocol}#{request.host_with_port}" + '\1"')
end
Run Code Online (Sandbox Code Playgroud)