views:

343

answers:

2

In Datamapper, how would one specify the the combination of two fields must be unique. For example categories must have unique names within a domain:

class Category
  include DataMapper.resource
  property :name, String, :index=>true #must be unique for a given domain

  belongs_to :domain
end
A: 

Did you try to define both properties as keys? Not sure I have tried it but that way they should become a composite key.

property :name, String, :key => true    
property :category, Integer, :key => true
Jonas Elfström
Actually there already is a key, I just didn't include it in the code snippet.
John F. Miller
A: 

You have to create a unique index for the two properties:

class Category
  include DataMapper::Resource

  property :name, String, :unique_index => :u
  property :domain_id, Integer, :unique_index => :u

  belongs_to :domain
end
joschi
This is incorrect as it will require that both name and domain be unique across the table. What I asked was how to make the set (:name, :domain) unique.
John F. Miller