In rails 3.2.3, I want to validate that a link model has a unique combination of two fields. I have a test and a validation that passes the test as shown below, but it seems there may be a better way to do this. For instance, would it be better to use an index with uniqueness? If so, why?
# link_test.rb
...
test "cannot create two links with same name and url" do
Link.create!(:name => 'example', :url => 'http://www.example.com')
assert_raise(ActiveRecord::RecordInvalid, 'could create two links with same name and url'){Link.create!(:name => 'example', :url => 'http://www.example.com')}
end
...
# link.rb
class Link < ActiveRecord::Base
...
validates :name, :uniqueness => {:scope => :url, :message => 'cannot have two entries with same name and url'}
...
end