I have a rails app with a Backbone.js front-end. In my Backbone model/collection definition, I have the following for a model (in project.js.coffee.erb)
#############################
## MODEL
#############################
class window.Project extends Backbone.Model
urlRoot: '/projects'
#############################
## COLLECTION
#############################
class window.Projects extends Backbone.Collection
model: Project
url: '/projects'
# initialize new collection
window.projects = new Projects
projects.reset(<%= Project.all.to_json %>)
The last line is where ERB loads in all the projects in JSON.
When I load my application, this bootstraping results in a collection that contains old data. I know it’s old because I’ve gone as far as to:
- delete my development database (sqlite3)
- alter my database.yml to rename my development database name
- re-run
rake db:migrateto create a brand new .sqlite3 database file
I can run sqlite3 and see that the projects table contains no rows, and yet, even after restarting the server, project.js is compiled to contain a collection full of now non-existent data.
Rails correctly boots into development mode when I run rails s:
=> Booting WEBrick
=> Rails 3.2.5 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-07-02 21:24:08] INFO WEBrick 1.3.1
[2012-07-02 21:24:08] INFO ruby 1.9.3 (2012-04-20) [x86_64-darwin11.4.0]
[2012-07-02 21:24:08] INFO WEBrick::HTTPServer#start: pid=11607 port=3000
If I create new projects, they even save to the database. They also get added to the Backbone collection just fine. But, again, if I reload the page or even restart the server, the collection is again populated with the old data.
Can someone help me figure out what I’m doing wrong here?
Ok, turns out I figured out what’s going on.
Assets in rails are cached so long as the file itself doesn’t change. So once
project.js.coffee.erbwas compiled intoproject.js, the data being bootstrapped into the collection would remain static until I made a change toproject.js.coffee.erb, at which point rails would re-compile the file, only then re-fetching the data from the database.I realized that if I want new data to be bootstrapped into the collection on each page load, I’d need to add the
projects.reset()javascript as an inline script in the mainapp/views/layouts/application.html.haml. Adding this code to the end of mybodytag did the trick.Now, each time the page is reloaded, the current data is loaded into the appropriate collections.