Rails Asset Pipeline When Application is Deployed in a Subdirectory

The asset pipeline is great and confusing at the same time. It performs differently in development than it does in production, and as such you can’t be really sure everything is going to work once you deploy it, unless you really understand it, of course.

One thing I spent 5 hours banging my head over was related to the jquery-datatables-rails gem. The gem includes some small images referenced via CSS that are used with the tables and they were displaying as expected in development. Once I deployed to my production box running Passenger, however, the CSS was malformed, preventing the images from showing. For example, the images showing the sort direction of a table had this CSS in development:

.sorting_asc {
    background: url("/assets/dataTables/sort_asc.png") no-repeat scroll right center transparent;
}
.sorting_desc {
    background: url("/assets/dataTables/sort_desc.png") no-repeat scroll right center transparent;
}
But in production, there were only empty tags:
.sorting_asc {
}
.sorting_desc {
}

After hours of trying different combinations of settings in config/environments/production.rb and Googling, I narrowed it down to having something to do with my application in production being deployed in a subdirectory on the web server. What I mean by that is that instead of going to http://mycoolapp.server.com to get to my application, I had to go to http://server.com/mycoolapp.I eventually stumbled on the “Gotchas” post in the references below. It explained that the different context of the application required telling the rake assets:precompile task to create the correct URL references when the assets were generated. Why the wrong URL wasn’t shown in the CSS is beyond me – at least that would have pointed me in the right direction more quickly. The key is adding the RAILS_RELATIVE_URL_ROOT variable definition when you run the precompile rake task.

My final asset compilation script for production became:

bundle exec rake assets:clean && bundle exec rake assets:precompile RAILS_ENV=production RAILS_RELATIVE_URL_ROOT="/mycoolapp"

Hope this helps someone and saves them some time…

References

Rails 3.2 and Asset Pipeline Gotchas

 

One thought on “Rails Asset Pipeline When Application is Deployed in a Subdirectory”

Leave a Reply

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