0
在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