在 rails 3.2.3 中,我想验证链接模型是否具有两个字段的唯一组合。我有一个测试和一个通过测试的验证,如下所示,但似乎有更好的方法来做到这一点。例如,使用具有唯一性的索引会更好吗?如果是这样,为什么?
# 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