August 16, 2010

Storing Arrays in a Database Field w/ Rails ActiveRecord

When I first started writing Expendite, an expense sharing web application targeted toward apartment-mates, I barely knew Rails. For each expense, I needed a way to record which users were involved as parties. Basically I needed a many-to-many association with a join table, though I didn't know it at the time.

Embarrassingly, I chose the method of storing an array of user id's (the involved parties) in a parties column in my database. Now I know better, but it still may be useful to know how to store arrays in a database that seemingly doesn't have any support for array objects.

Luckily, ActiveRecord has this support built right in!

First, the column in question should be changed to type text. If you've already created and used your database, a simple database migration is in order. Next, serialize the column:

class Expense < ActiveRecord::Base
    serialize :parties
    # other model code
end

That's literally all you need to do! Now, just save an array to the column like you would normally save a field value:

Expense.new(:parties => [1, 2, 3])

And when you call the parties on an Expense again, it'll spit an array back at you. It's also worth noting that this technique may be used for hashes as well!

Note: Storing arrays in databases is most likely not what you want to do.

There's probably a relationship/associations solutions (like my anecdote), or you can figure out another way to make it work with multiple columns.