Full url for an image-path in Rails 3

前端 未结 9 1501
说谎
说谎 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:55

    There's quite a bunch of answers here. However, I didn't like any of them since all of them rely on me to remember to explicitly add the port, protocol etc. I find this to be the most elegant way of doing this:

    full_url = URI( root_url )
    full_url.path = Image.first.image.url
    # Or maybe you want a link to some asset, like I did:
    # full_url.path = image_path("whatevar.jpg")
    full_url.to_s
    

    And what is the best thing about it is that we can easily change just one thing and no matter what thing that might be you always do it the same way. Say if you wanted to drop the protocol and and use the The Protocol-relative URL, do this before the final conversion to string.

    full_url.scheme = nil
    

    Yay, now I have a way of converting my asset image urls to protocol relative urls that I can use on a code snippet that others might want to add on their site and they'll work regardless of the protocol they use on their site (providing that your site supports either protocol).

提交回复
热议问题