8

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
John F. Miller
  • 25,556
  • 8
  • 66
  • 120

3 Answers3

16

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
  • 11,459
  • 4
  • 40
  • 47
  • 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 Mar 24 '10 at 00:06
  • Indeed, although the `:u` symbol could have been clearer -- for example `:index_on_name_and_domain_id` -- it actually is correct. See the section Indices on the DataMapper property documentation page: http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Property. The statements create a multi-column composite unique index. – Jochem Schulenklopper Feb 18 '13 at 20:06
2

Actually, John, Joschi's answer is correct: the use of named :unique_index values does create a multiple-column index; it's important to read the right-hand side of those hash-rockets (i.e., if it had just been true, you would be right).

cobbr2
  • 111
  • 1
  • 2
1

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
  • 28,718
  • 6
  • 66
  • 102