验证DataMapper中组合字段的唯一性

sch*_*ift 3 ruby validation datamapper sinatra

我希望能够在我的数据库中放置条目,其中制造商将被多次代表但不是制造商和型号的相同组合.所以"索尼(制造商),电视(型号)"还可以"索尼(制造商),OtherTv(型号)",但第三个条目"索尼(制造商),电视(型号)"自制造商和型号组合以来并不合适不是唯一的.我尝试了:key => true验证,但似乎没有用.而且我不能像validates_uniqueness_of :manufacturer AND :model我猜的那样做.你是怎么做到的?

class Tvs
  include DataMapper::Resource

  property :id,           Serial
  property :manufacturer, String, :key => true
  property :model,        String, :key => true

  validates_uniqueness_of :
end
Run Code Online (Sandbox Code Playgroud)

小智 5

你可以真的去:

class Tvs
  include DataMapper::Resource

  property :id,           Serial
  property :manufacturer, String, :unique_index => :manufacturer_model
  property :model,        String, :unique_index => :manufacturer_model

  validates_uniqueness_of :model, :scope => :manufacturer
end
Run Code Online (Sandbox Code Playgroud)

这也将为您提供数据库中的唯一索引.