CarrierWave full url for default image

2019-05-07 02:33发布

问题:

I am using CarrierWave for image uploads on a rails-api application which in turn is consumed by a backbone.js client app. I notice that when there is no default image available it returns /assets/default.png. It in turn has to be http://dev-server:3000/assets/default.png. Here are my configuration settings:

# config/environments/development.rb
CarrierWave.configure do |config|
  config.asset_host = "http://dev-server:3000"
end

# Image Uploader
....

def default_url
  "/assets/default.png"
end

Where am I going wrong?

回答1:

[Edit (updated answer)]

Updating my answer to setup asset_host in rails config.

Rails.application.configure do
  .
  .
  config.asset_host = 'http://dev-server:3000'
end

Then you can use asset_url method or image_url method of the helper. Since this is an image, I would recommend placing the image in app/assets/images folder and use image_url.

ActionController::Base.helpers.image_url("default.png")

This will give you the following URL:

http://dev-server:3000/images/default.png

You can try it in the console.

[Old Answer]

Looking at Carrierwave Documentation, it seems like your default_url method should look like this (Carrierwave does not automatically perpend asset_host to the default url):

def default_url
  ActionController::Base.helpers.asset_path("default.png")
end

I am assuming that asset_host is setup properly in your Rails configuration. If not, please do so.



回答2:

I'm using Rails 5 API and Carrierwave too.

A lucky guess got it working for me.

I have a file inside app/uploaders/image_uploader.rb.

The asset_host configuration is set inside this file (at least it works for me):

# encoding: utf-8

class ImageUploader < CarrierWave::Uploader::Base

  ...

  def asset_host
    return "http://localhost:3000"
  end

end

Hope this works for anyone else in the future having this problem.



回答3:

I would recommend some of your ideas:

I: Put Host in your environment z.B. development.rb

config.asset_host = 'http://localhost:3000'

II: Create file in config/initializers/carrierwave.rb

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

III: Edit your uploader to:

def default_url
    "#{asset_host}/images/fallback/" + [version_name, "default.png"].compact.join('_')
  end

IV: RESTART your server



回答4:

I solved the problem by looking into the code of carrierwave. This is what I ended up doing:

  def default_url
    "#{asset_host}#{ActionController::Base.helpers.asset_path("default.png")}"
  end

Also make sure that you include the asset_host configuration in your respective environment files.