Loading and managing reference data in Rails
Most of the apps I've worked on have had some kind of reference data stored in the database, for example categories, zipcodes, area codes etc... this is information that's going to change very infrequently. Most of the time you want to load some kind of display name, and that's it.
Currently this isn't causing me too many headaches, it's easy to :include th开发者_如何转开发e models I need when doing my queries, but going forward it causes a lot of query noise.
Ideally I'd like to load the reference data when the app starts and when referencing it in queries it'll load from the cache instead of going to the database.
What's the best way to manage this?
This is a great question, and one that most Rails developers have probably had to deal with at some point. I've tried loading everything into a constant on boot. I've also tried using Memcached or Redis with a plugin like cached_model or cache_fu and automatically populate the cache when the application boots. However, these approaches only work for finding single objects, and don't integrate with ActiveRecord at all (eg, don't work with associations), as I'm sure you've noticed.
There's an obvious market for a Memcached/Redis plugin with better ActiveRecord integration, but it sounds like an awfully difficult undertaking so I don't think we're likely to see anything soon.
Making the situation worse is the fact that if you're pre-loading a lot of data, you probably don't want to do it on every request in the development environment, which is hard to avoid because models are lazy-loaded (and reloaded on every request) in development and presumably you need the model to load the data. This means that a good solution must be tightly integrated with ActiveRecord so it works whether the data is coming from the DB or the cache (if you don't pre-load in development).
Anyway, sorry for the long-winded non-answer, but I think discussion may be the best we can do at this point.
Hopefully I'm wrong. Anybody?
Just use renum-gem to define such data and has_enum-gem for a drop in rails integration.
精彩评论