Fixes race condition in resources

See #1378.

Don't merge yet! Either there's something slightly broken, or I messed up my database while testing things earlier, and either way it hasn't been tested very much yet. I just wanted to get the partial work onto Github.