Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 836
schwift Avatar asked Feb 11 '26 20:02

schwift


1 Answers

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.

like image 112
namelessjon Avatar answered Feb 16 '26 19:02

namelessjon