Rails 5 Assets Not Loading in Production - ruby-on-rails

I recently updated a few packages in my Rails application and now my assets aren't being served. Instead, I get the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)
My assets are precompiled:
assets.rb
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path
# Rails.application.config.assets.paths << Emoji.images_path
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# Rails.application.config.assets.precompile += %w( search.js )
Rails.application.config.assets.precompile += %w(ckeditor/*)
Rails.application.config.assets.precompile += %w(ckeditor/config.js)
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module DeployTest
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.assets.precompile += Ckeditor.assets
config.assets.precompile += %w( ckeditor/* )
config.autoload_paths += %W(#{config.root}/app/models/ckeditor)
config.active_record.default_timezone = :local
config.time_zone = 'Eastern Time (US & Canada)'
end
end
Before telling me to turn on compiling my assets, please understand that this is
a horrible idea. Thank you for any advice
UPDATE: I got it to work by adding:
config.assets.digest = true
to my config/environments/staging.rb file. Weird how I didn't need it before

At times you need to add both of these configurations in staging.rb or whichever environment you want the changes to reflect on.
config.assets.compile = true #set to false by default
config.assets.digest = true

Related

NoMethodError: undefined method `eager_load_paths' for #<I18n::Config:0x00007fceade8c0f0>

In my rails 6 app running ruby 2.7, I am trying to eager load all the files using Zeitwerk. Here is a snippet of my application.rb file:
class Application < Rails::Application
config.load_defaults "6.0"
Zeitwerk::Loader.eager_load_all
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
# Middlewares
config.middleware.insert 0, Rack::UTF8Sanitizer
config.middleware.use Rack::Attack
config.autoload_paths += Dir["#{config.root}/lib/**/*"]
config.autoload_paths += Dir["#{config.root}/app/models/**/*"]
config.autoload_paths += Dir["#{config.root}/app/observers/*"]
config.autoload_paths += Dir["#{config.root}/app/middleware/*"]
config.autoload_paths += Dir["#{config.root}/app/validators/**/*"]
config.autoload_paths += Dir["#{config.root}/app/**/concerns/*"]
config.autoload_paths += Dir["#{config.root}/app/operations/**/*"]
config.autoload_paths += Dir["#{config.root}/app/scrubbers/**/*"]
config.autoload_paths += Dir["#{config.root}/app/workers/**/*"]
config.paths.add "#{config.root}/app/operations/", eager_load: true
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = "UTC"
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')].reject { |f| File.fnmatch("#{Rails.root.to_s}/config/locales/**/x_*.yml", f) }
config.i18n.available_locales = [:"en", :"fr", :"fr_en"]
config.i18n.default_locale = :en
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
config.assets.precompile += ["public.css", "public.js", "public_payments.js", "email.css", "pdf.css", "pronotif.css"]
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
However, when I run this I get this error:
NoMethodError: undefined method `eager_load_paths' for #<I18n::Config:0x00007fceade8c0f0>
Any solution for this will be helpful
Problem
Aside from the fact that your application.rb is not in a good shape (as #max mentioned in the first comment to your question) the problem is known and already fixed for Rails.
Unfortunately (as time of writing, with Rails 6.0.2.2) the fix is currently not public.
Temporary Workaround
But until then you might copy the patched rake task to your app under a file named lib/tasks/local_zeitwerk.rake and change line 41 to:
namespace :local_zeitwerk do
and then execute the check task with
bin/rails local_zeitwerk:check

I have problem with ckeditor in my Rails project

I use tutorial - https://github.com/galetahub/ckeditor/
And add cktext_area in _form
<%= f.label :body %>
<%= f.cktext_area :body %>
But it is not displayed
I use
gem 'carrierwave'
gem 'mini_magick'
In application.js require adding, routes modified, but not working at all, and use command
rails generate ckeditor:install --orm=active_record --backend=carrierwave.
Help!!!
assets.rb
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
Rails.application.config.assets.precompile += %w( ckeditor/*)
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
Rails.application.config.assets.precompile += %w[bootswatch.scss]
# Precompile additional assets.
# application.js, application.scss, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )

Rails won't precompile the assets-fonts folder

I kept getting a 404 on my application, only to realize that it is looking for a font: /assets/fonts/footable.woff
So I figured I'd just create the fonts folder within my app/assets folder, and then re-run RAILS_ENV=production rake assets:precompile
I did this, and when I do an ls to public/assets/, there is still no fonts folder.
Here's my config/application.rb
module MyRailsApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
config.time_zone = "Central Time (US & Canada)"
config.active_record.default_timezone = :local # Or :utc
config.eager_load_paths += Dir["#{config.root}/lib/custom_rb/**/"]
config.assets.enabled = true
config.assets.paths << Rails.root.join("app", "assets", "images", "iCheck")
config.assets.paths << Rails.root.join("app", "assets", "fonts")
# For sidekiq
#config.active_job.queue_adapter = :delayed_job
config.active_job.queue_adapter = :sidekiq
end
end
and here's my config/initializers/assets.rb file:
# Be sure to restart your server when you modify this file.
# Version of your assets, change this if you want to expire all your assets.
Rails.application.config.assets.version = '1.0'
# Add additional assets to the asset load path.
# Rails.application.config.assets.paths << Emoji.images_path
# Add Yarn node_modules folder to the asset load path.
Rails.application.config.assets.paths << Rails.root.join('node_modules')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in the app/assets
# folder are already added.
# Rails.application.config.assets.precompile += %w( admin.js admin.css )
Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
I have also restarted apache, and it's still not there.
What am I doing wrong?

Rails Engine assests are not precompiled

I am studying rails and using the engines with rails.
In production mode, rails did not load compiled assets of engines,
although I have executed:
$ RAILS_ENV=production bundle exec rake assets:clean assets:precompile
Please help if anyone knows the issue.
My settings are as below:
environment/production.rb
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = false
config.assets.compile = false
config.assets.digest = true
config.log_level = :debug
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new`
engine/xxx/lib/xxx/engine.rb
Engines's option is -- mountable
module Moderna
class Engine < ::Rails::Engine
isolate_namespace xxx
# parent company asset precompile
initializer "xxx.assets.precompile" do |app|
app.config.assets.paths << Rails.root.join("app", "assets", "fonts")
app.config.assets.precompile << %w(
xxx/*.css xxx/fancybox/*.css xxx/skin/*.css xxx/google-code-prettify/*.css
xxx/*.js xxx/flexslider/*.js xxx/google-code-prettify/*.js
xxx/portfolio/*.js xxx/quicksand/*.js
xxx/*.svg xxx/*.eot xxx/*.woff xxx/*.ttf
xxx/customicon/*.svg xxx/customicon/*.eot xxx/customicon/*.woff xxx/customicon/*.ttf
)
app.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
end
end
end
The rails engine getting started guide suggests including the following in your engine.rb
initializer "engine_name.assets.precompile" do |app|
app.config.assets.precompile += %w( admin.js admin.css )
end
It works for me.
I faced same issue with Rails 4 engine, I resolved by adding following code to engine.rb
Rails.application.config.assets.precompile += ['*.js', '*.css', '**/*.js', '**/*.css', '*.jpg',
'*.png', '*.ico', '*.gif', '*.woff2', '*.eot',
'*.woff', '*.ttf', '*.svg']
I need to precompile all assets so wild cards are used. You can specify files.
Second option is you can specify on Host applications
config/assets.rb
Rails.application.config.assets.precompile += %w( engine_name/file_name )
EDIT Just realised this question is a bit old. The below will work for you if you add an app/assets/config/my_component_manifest.js file to your engine and then use that to specify asset entry points.
You an also put it in the engine.rb file:
module MyComponent
class Engine < ::Rails::Engine
config.assets.precompile += %w( my_component_manifest.js )
end
end

Advice with organizing .js files in my rails app

I've got a rails app that's driving me crazy. I can't figure out why I'm getting duplicate js calls. I'm guessing it's something to do with the ordering or organization of the application.js require statements and the location of the .js files. I've also tried screwing around with production.rb and usually only make the .js completely broken with that. Here's what I've got:
app
|assets
||javascripts
|||+data_centers
|||-data_center.js
||-application.js
||-rails.js
vendor
|assets
||javascripts
||-autocomplete-rails.js
||-jquery-1.9.1.js
||-jquery-ui-1.10.2.custom.js
application.js has the following require statements:
//= require jquery-1.9.1
//= require jquery-ui-1.10.2.custom
//= require twitter/bootstrap
//= require bootstrap-typeahead
//= require rails
//= require autocomplete-rails
data_center.js has the following require statements:
//= require highcharts
//= require highcharts/modules/canvas-tools
//= require highcharts/modules/exporting
Before, I had the .js files from vendor/assets in app/assets but was advised to keep all external .js in the vendor/assets location. Point is that doesn't work.
My production.rb looks like this:
MyApp::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
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
#default false ^^
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
#defualt false
# Compress JavaScripts and CSS
config.assets.compress = false
#defualt true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
#default = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# 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
# See everything in the log (default is :info)
# config.log_level = :debug
# 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 are already added)
# config.assets.precompile += %w( search.js )
# config.assets.precompile += %w( jquery.js )
# config.assets.precompile += %w( jquery_ujs.js )
# config.assets.precompile += %w( jquery-ui-1.10.2.custom.js )
# config.assets.precompile += %w( twitter/bootstrap.js )
# config.assets.precompile += %w( bootstrap-typeahead.js )
# config.assets.precompile += %w( rails.js )
# config.assets.precompile += %w( autocomplete-rails.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# 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
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
Please let me know if you have any ideas. Thanks.
You could try config.assets.debug = true in your production.rb to get a better picture, but I'd suggest first trying to debug problems with assets in development.
Some gems or their dependencies may be loading assets that you might not have been aware of.
In Rails console in the environment you are interested in (i.e. you might need to ssh to the server, etc. and/or set the environment in/before the command):
rails c
you might use the following to get a little more info from Sprockets about current assets:
Rails.application.assets.each_file {|path| begin; Rails.application.assets[path].dependencies.each{|d| puts "#{path} dependencies: /assets/#{d.logical_path}"}; rescue; puts "#{path}"; end}
Then you might look at gem list in your prod environment or look at Gemfile.lock to see what gems bundler is using. Maybe assets are being loaded that you didn't know about.
For asset organization, see the guide.
Also, consider that the guide suggests some different settings than what you are using in your production config, e.g. it suggests using config.assets.compress = true and to set config.serve_static_assets = false and have apache or nginx serve static assets, for performance reasons.

Resources