Heroku and Rails 3.2 asset:precompile error

This article targets Rails ~> 3.2

The article was written as of Rails 3.2. The information contained in this page might not apply to different versions.

I have a very simple Rails 3.1 application, deployed on Heroku. Just after upgrading it to Rails 3.2, the deploy to Heroku stopped working properly.

More specifically, the rake asset:precompile task was failing during slug compilation.

``` Your bundle is complete! It was installed into ./vendor/bundle Cleaning up the bundler cache. —–> Writing config/database.yml to read from DATABASE_URL —–> Preparing app for Rails asset pipeline Running: rake assets:precompile rake aborted! could not connect to server: Connection refused Is the server running on host “127.0.0.1” and accepting TCP/IP connections on port 5432?

   Tasks: TOP => environment
   (See full trace by running task with --trace)
   Precompiling assets failed, enabling runtime asset compilation
   Injecting rails31_enable_runtime_asset_compilation
   Please see this article for troubleshooting help:
   http://devcenter.heroku.com/articles/rails31_heroku_cedar#troubleshooting ```

The Heroku assets:precompile toubleshooting page contains several explanations, but none of these was my case. In fact, my application was working properly with Rails 3.1.

It turns out there are some changes in the Rails 3.2 initialization process that conflicts with Heroku slug compilation. The solution is very simple. All you have to do is to set the Rails 3.2 initialize_on_precompile configuration to false in your application.rb file.

ruby config.assets.initialize_on_precompile = false

This option is new in Rails 3.2 and prevents the Rails environment to be loaded when the assets:precompile task is executed. Because Heroku precompile assets before setting the database configuration, you need to set this configuration to false or you Rails application will try to connect to an unexisting database.

Your bundle is complete! It was installed into ./vendor/bundle Cleaning up the bundler cache. -----> Writing config/database.yml to read from DATABASE_URL -----> Preparing app for Rails asset pipeline Running: rake assets:precompile -----> Rails plugin injection Injecting rails_log_stdout Injecting rails3_serve_static_assets ...

This configuration is also documented in the Precompiling Assets section of the new Rails 3.2 asset pipeline guide.