Full url for an image-path in Rails 3

前端 未结 9 1409
说谎
说谎 2020-12-13 09:14

I have an Image, which contains carrierwave uploads:

Image.find(:first).image.url #=> \"/uploads/image/4d90/display_foo.jpg\"

In my vie

相关标签:
9条回答
  • 2020-12-13 09:38

    Just taking floor's answer and providing the helper:

    # 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
    
    0 讨论(0)
  • 2020-12-13 09:39

    try path method

    Image.find(:first).image.path
    

    UPD

    request.host + Image.find(:first).image.url
    

    and you can wrap it as a helper to DRY it forever

    request.protocol + request.host_with_port + Image.find(:first).image.url
    
    0 讨论(0)
  • 2020-12-13 09:41

    Another simple method to use is URI.parse, in your case would be

    require 'uri'
    
    (URI.parse(root_url) + image.url).to_s
    

    and some examples:

    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" 
    
    0 讨论(0)
  • 2020-12-13 09:42

    I used default_url_options, because request is not available in mailer and avoided duplicating hostname in config.action_controller.asset_host if haven't specified it before.

    config.asset_host = ActionDispatch::Http::URL.url_for(ActionMailer::Base.default_url_options)
    
    0 讨论(0)
  • 2020-12-13 09:42

    I found this trick to avoid double slash:

    URI.join(root_url, image.url)
    
    0 讨论(0)
  • 2020-12-13 09:44

    You can actually easily get this done by

    root_url[0..-2] + image.url
    

    I agree it doesn't look too good, but gets the job done.. :)

    0 讨论(0)
提交回复
热议问题