Validate composite keys in Rails 3

Suppose you have a ‘families’ table in your database with a ‘husband’ and ‘wife’ column. You add a a composite key so that the combination husband and wife is unique. You certainly don't want another record with the same husband and wife combination. At the database level your migration could look like this:

  add_index :families, [:husband, :wife], :unique => true
  

Validations in Rails 2.x

Now you want to add a corresponding validation in your family model. In Rails 2.x we can use a scope:

  validates_uniqueness_of :husband, :scope => :wife
  

Validations in Rails 3

In Rails 3 this looks slightly different:

  validates :husband, :presence => true, :uniqueness => {:scope => :wife}
  

I wouldn't have found this without the help of KandadaBoggu and epochwolf on the stackoverflow forum, thanks guys!

This post is open source. Did you spot a mistake? Ideas for improvements? Contribute to this post via Github. Thank you!