CSS doesn't load on Heroku, when I enabled an

2019-08-30 07:13发布

问题:

I have an app on Heroku and finally managed to save uploaded images (using Carrierwave) to Amazon S3, they show in my bucket and all is fine, but I had to add this to my production.rb:

# Enable serving of images, stylesheets, and JavaScripts from an asset server.
config.action_controller.asset_host = "https://s3-us-west-1.amazonaws.com/mybucket"

However now there is something wrong with my asset pipeline. It looks for the CSS and Javascript from the config.action_controller.asset_host and I would like to load them normally on Heroku. I tried adding this, but it didn't work:

# Precompile additional assets. application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
  config.assets.precompile += %w( 'custom.css.scss' )

I also tried to run RAILS_ENV=production bundle exec rake assets:precompile

On localhost everything works fine, but when I push to heroku, then the CSS brakes.

Many thanks in advance for any help!

回答1:

This is a sample code taken directly (but slightly modified) from the documentation of asset_host

ActionController::Base.asset_host = Proc.new { |source|
  if source.ends_with?('.css')
    "http://myapp.herokuapp.com"
  else
    "http://assets.example.com"
  end
}

image_tag("rails.png")
# => <img alt="Rails" src="http://assets.example.com/assets/rails.png" />
stylesheet_link_tag("application")
# => <link href="http://myapp.herokuapp.com/assets/application.css" media="screen" rel="stylesheet" />