Rails 4 and Rake task gotcha

August 23, 2013

By John Beynon


There's presently a bug in Rails 4.0.0 that can cause you issues deploying your application to services like Heroku.

In short, a validation such as

validates_acceptance_of :terms, allow_nil: false

can result in your application becoming undeployable for the first time on Heroku.

When you do try and deploy it for the first time, gems are bundled etc and then assets are attempted to be precompiled via a rake task, the problem is that this fails because Rails isn't doing what it say it's doing in the comment of production.rb

# 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

At the moment Rails is still loading code so and the particular validation above requires a database hit to see if the model responds to the virtual attribute - and being a new application the database doesn't actually exist yet so the deployment fails.

This has been fixed in this pull request but it's not made it out into general release yet.

A quick fix, if you run into this problem is to not eager load on that initial deployment (config.eager_load = false), changing it back to true when you've deployed successfully and having run your migrations.

If your application has already been deployed when you add a validation like this and you've given your application access to the environment variables (via user-env-compile lab) then the problem won't appear and applications will deploy fine.

We've also found this affects other gems such as redactor-rails.