Active Record 4 now has support for PG's Array data-type. Here's how you might use it to give users multiple email addresses:
Migration:
class AddEmailsToUser < ActiveRecord::Migration
def change
add_column :users, :emails, :string, array: true, default: '{}'
end
end
Notice:
* it's specified as data type :string with array: true
* to default the column to an empty array ( [] ), you use default: '{}'
To query your records you want to use PSQL's ANY and/or ALL methods:
SELECT * FROM users WHERE 'foo@bar.com' = ANY (emails);
SELECT * FROM users WHERE 'foo@bar.com' = ALL (emails);
...which behave as you'd imagine.
Using the Active Record query API:
User.where("'foo@bar.com' = ANY (emails)")
That's it! I hope that helps someone.
BONUS EDIT 2013-07-15:
To create an index for your array column, you must choose between GiST and GIN as strategies. The documentation covers the options nicely, but the distilled version is that GIN lookups are much (3x) faster, but take longer (10x) to build. If your data is read far more often than it is written, go for GIN.
You'd do that with the following (AR4) migration:
class AddEmailIndexToUsers < ActiveRecord::Migration
def change
add_index :users, :emails, using: 'gin'
end
end
~ Stu
Excellent, thanks for this!