开发者

Validate uniqueness on combined fields in DataMapper

I want to be able to put entries in my database where the manufacturer will be represented multiple times but not the same combination of manufacturer and model. So "Sony(manufacturer), Tv(model)" is okay "Sony(manufacturer), OtherTv(model)" but the third entry "Sony(manufacturer), Tv(model)" is not okay since the combination of manufacturer and model is not unique. I tried with the :key => true validation but it doesn't seem to work. And I cannot do something like validates_uniqueness_of :manufacturer AND :model I guess. So how do you do it?

class Tvs
  include DataMapper::Resource

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

  validates_uniqueness开发者_高级运维_of :
end


You can actually go with:

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

This will also give you a unique index in the database.


Nevermind. It seems this did the job:

class Tvs
  include DataMapper::Resource

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

  validates_uniqueness_of :model, :scope => :manufacturer
end


class Tvs
  include DataMapper::Resource

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

  validates_is_unique :model, :scope => :manufacturer
end

I needed to modify the example to use "validates_is_unique" to get this to work.


If you remove the property :id Serial line, you will end up with a composite key (Manufacturer, Model), that will not allow duplicate Models for a particular Manufacturer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜