Implementing a lookup table in Rails

2019-04-07 21:06发布

问题:

I'm currently using (or trying to use) a lookup table to represent a column that contains an enumerated string. I've had extensive discussions with my team to make sure this is the direction we want to go and have decided to pursue it but unfortunately none of us know how to tie the lookup table to the column using migrations and if there are changes that have to be made in the model/controller/views to support this new behavior.

I've googled this extensively and have not found good examples of doing this so I'm hoping someone can either tell me of a wonderful link to a tutorial I just missed in my search, or describe how to do this. I also would love to know if there is an unofficial (or official) Railsy pattern for this.

Thanks in advance.

回答1:

I encountered the same problem as you, and solved it by creating a gem that adds a dynamic lookup table transparently into the model. I've blogged about it here: http://www.codelord.net/2011/08/09/guest-post-lookup-tables-with-ruby-on-rails/

And the code is here: https://github.com/Nimster/RailsLookup



回答2:

If you're looking for a light-weight way to model enumerations/configuration without creating a separate table, definitely check out ActiveHash:

https://github.com/zilkey/active_hash



回答3:

Do you really need it to be in the database?

If it is just a short list, a static array (loaded from a CSV file) might be enough.