Validate composite keys in Rails 3

Comparing model validations between Ruby on Rails 2 and 3 with composite database keys.

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

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

Validations in Rails 2

Now you want to add a corresponding validation in the ‘family’ model. In Ruby on Rails 2 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 stackoverflow.