user2956850
user2956850

Reputation: 33

Rails 5 Assets not compiling images or css

I would appreciate any help great. I recently updated my app to rails 5.2.3 (from 4.0.1) and noticed that when I added a new image to assets/images it failed to display in production. I ended up running rake assets:clobber and tried to rebuild my assets with rake assets:precompile. Unfortunately now all my assets are dead.

Everything works as expected in development when I start a rails server and go to localhost:3000

I have tried tinkering with the production.rb configuration file but have made no progress. Any help would be appreciated, I have put a lot of work into this website and it used for medical professionals around the world. I am not a professional programmer by any stretch. I notice that after running

assets:precompile RAILS_ENV=production

A new public/assets folder was created but only contains three files:

instead of all the images i have in my assets/images folder

production.rb

BoardsApp::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both thread web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable Rails's static asset server (Apache or nginx will already do this).
  config.serve_static_assets = false

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = false

  # Generate digests for assets URLs.
  config.assets.digest = true

  # Version of your assets, change this if you want to expire all your assets.
   config.assets.version = '1.0'

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Set to :debug to see everything in the log.
  config.log_level = :info

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = "http://assets.example.com"

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

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Disable automatic flushing of the log to improve performance.
  # config.autoflush_log = false

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new
end

Gemfile

source 'https://rubygems.org'
ruby '2.6.3'
gem 'rails', '5.2.3'
gem 'puma'
gem 'bootstrap-sass'
gem 'bootstrap-switch-rails'
gem 'nokogiri'
gem 'pg', '0.21.0'
gem 'haml'
gem 'friendly_id'
gem 'rake'

group :development, :test do
  gem 'rspec-rails'
end

group :test do
  gem 'selenium-webdriver'
  gem 'capybara'
end
  
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder'

group :doc do
  gem 'sdoc', require: false
end

group :production do
  gem 'rails_12factor', '0.0.2'
end

Update I restored the website from an earlier deployment on Heroku so at least its alive for now but I have not resolved the issue of how to update since none of my images appear to be compiling.

When I run rails server in production I get this error:

ActionController::RoutingError (No route matches [GET] "/stylesheets/application.css"):
ActionController::RoutingError (No route matches [GET] "/javascripts/application.js"):

whereas in development everything loads as expected. UPDATE SOLVED! Thank you for the suggestion to look in the heroku logs. I found the error:

Asset `application.css` was not declared to be precompiled in production

From there I found https://github.com/rails/sprockets-rails/issues/458 this discussion.

I downgraded my sprockets-rails gem to 2.3.3. and ran rake assets:precompile again and everything was in working order.

Upvotes: 3

Views: 2524

Answers (1)

Promise Preston
Promise Preston

Reputation: 29068

I had this same issue when working on a Rails 6 application in Ubuntu 20.04.

The issue for me was that I was not serving the precompiled assets properly in production..

Here's how I fixed it:

First, I ran the command below to precompile the assets and make them available in the public directory of my application:

rails assets:precompile RAILS_ENV=production

This compiles and copies images, css and js from app/assets and app/javascript to public/.

Note: In development, this can be accomplished using webpacker with the command: /bin/webpack-dev-server

Next, set up Nginx or Apache web server to serve the static files that are available in the public directory of my application. For me I set up Nginx with the configuration below using Let's Encrypt for SSL:

upstream railsserver {
        server 127.0.0.1:3000;
}

server {

        # Replace 'localhost' with your FQDN if you want to use
        # your app from remote or if you need to add a certificate 
        server_name my-website.com www.my-website.com;
                        
        root /home/deploy/my-website/public;

        # Define where Nginx should write its logs
        access_log /var/log/nginx/my-website/access.log;
        error_log /var/log/nginx/my-website/error.log;

        location / {
            # First attempt to serve request as file, then
            # the rails application directory
            try_files $uri @railsserver;
        }
       
        location ~ ^/(assets/|robots.txt|humans.txt|favicon.ico) {
                expires max;
        }

        location @railsserver {
                proxy_set_header Host $http_host;
                proxy_set_header CLIENT_IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_read_timeout 300;
                proxy_pass http://railsserver;

                gzip on;
                gzip_types text/plain text/xml text/css image/svg+xml application/javas$
                gzip_proxied any;
        }

        listen [::]:443 ssl ipv6only=on; # managed by Certbot
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/my-website.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/my-website.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

That's all.

I hope this helps

Upvotes: 1

Related Questions