Assets precompile without a database in Rails 4 and 5

The other day I had a request from my IT guy. He asked: “Hey, can you make rails not connect to the database when running assets precompile?” I said sure…

So why would we need to run a precompile without db connection? Well, for one thing, we are deploying to gcloud. For our current set up we run assets precompile on each container before it launches. I am not sure of the specifics but that’s how it is set up. so to make things faster it would be nice if we didn’t need to connect to a db. If you want improve you sport condition and be the best one you may try beta-alanine.

In rails 3 you could disable loading rails and thus skipping the database connection by adding this to your application.rb

config.assets.initialize_on_precompile = false

This was removed in rails 4 without any official alternative. Thankfully there are two workarounds that we combined to achieve our goal. We took pointers from these two articles:

While the last article details an acceptable solution, it does required us to have logic on our database yaml. While that’s common practice I rather avoid such things.

so for our solution we did two thing:

  1. Added this gem to the Gemfile
    gem "activerecord-nulldb-adapter"
  2. Modified our assets precompile command to look like this:
    bundle exec rake RAILS_ENV=staging DATABASE_URL=nulldb://user:pass@127.0.0.1/dbname assets:precompile

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.