0
votes

I recently put a Rails app I've been working on up on Heroku. When I push to my Heroku git repository it runs the asset compilation as part of generating the slug. It was failing here with the following error:

could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port xxxx?

The problem is that the rake task, rake assets:precompile, is trying to connect to the database and my app does not have access to config vars during slug compilation. I found this information in Heroku's troubleshooting documentation and added the prescribed fix in my application.rb file:

config.assets.initialize_on_precompile = false

Now my assets get compiled correctly and the images in my gem's vendor/assets are usable.

Questions

  1. Why is the asset compilation rake task trying to connect to the database in the first place?
  2. Heroku also allows the assets to be compiled either locally and added to the git repo or during runtime. I believe these other two options won't run into the same problem as it only occurs during slug compilation. Is there any advantage in either of these?
2

2 Answers

1
votes
  1. The task will likely have a dependency on :environment, which will load your whole application, including the startup code, where the database connection is established.

  2. Asset precompilation serves the purpose to improve request time - rails doesn't have to compile the assets at every request. If you compile the assets locally, you are using your own machine, which most likely will be faster than the heroku env. You can easily use a hook to do the compilation automatically.

0
votes

config.initialize_on_precompile tells rake whether or not to load your full rails application during the asset compilation task, and that includes connecting to the database. As for compiling locally, no, there isn't much benefit to doing that.