Search code examples
ruby-on-railscsvruby-on-rails-4smartercsv

Rails: designing a model with unknown attributes


In my app I have a model called Address. The address field therein is the only required field, but the model can have any number of different other attributes.

Addresses will be created by importing rows from a .csv file. The CSV has to have an address column but may have many others, and they can be anything else and therefore impossible to predict.

How can I store this information accurately without having to add new DB columns each time? Can I make something like an extra DB column that stores information from columns not in the model? Can I run queries on that field (albeit bastardized)? Finally, when exporting this information back into CSV can I export that extra information back out?


Solution

  • One way to solve this is to use Postgres as a database and have a table with 2 columns: address and data where data is of jsonb type. What that gives you is an ability to push arbitrary key/value data. You still can query it via SQL and have indexes on those fields.

    Alternative would be to use a NoSQL database like Mongo or Couch.