Full url for an image-path in Rails 3

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

    You can't refer to request object in an email, so how about:

    def image_url(*args)
        raw(image_tag(*args).sub /src="(.*?)"/, "src=\"//#{ActionMailer::Base.default_url_options[:protocol]}#{ActionMailer::Base.default_url_options[:host]}" + '\1"')
    end
    
    0 讨论(0)
  • 2020-12-13 09:55

    You can also set CarrierWave's asset_host config setting like this:

    # config/initializers/carrierwave.rb
    CarrierWave.configure do |config|
      config.storage = :file
      config.asset_host = ActionController::Base.asset_host
    end
    

    This ^ tells CarrierWave to use your app's config.action_controller.asset_host setting, which can be defined in one of your config/envrionments/[environment].rb files. See here for more info.

    Or set it explicitly:

      config.asset_host = 'http://example.com'
    

    Restart your app, and you're good to go - no helper methods required.

    * I'm using Rails 3.2 and CarrierWave 0.7.1

    0 讨论(0)
  • 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).

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