Ruby on Rails - Categories as Hashes or Database Table
I have a general question about whether people think you should use a database table or constants hashes/a开发者_开发百科rrays for categories. I'm torn on which way to go. Thoughts?
Well, if you are 100% sure you won't ever change the categories, you could go for a custom model with the Object superclass (no DB-table and no ActiveRecord).
If you ever would change a category or add any you want a database. This is because your models won't get reloaded after a change in production mode.
I still recommend a database anyway because of at least the following:
- See MattC's comment.
- You can use ActiveRecord relationships (has_many and belongs_to). This is hard to do without ActiveRecord.
- The performance decrese is not significant. It might slow down 0.2ms at most.
Having them stored in the database (and used as a model) make it more flexible for the future. Adding/Removing new categories could be done without a redeploy of the app, whereas having them as hard-coded constant values would.
But with that said, it all depends on your specific needs. If you know for a fact that the categories will never change, constants might be better since that would mean less database hits.
精彩评论