datamapper multi-field unique index
Asked Answered
C

3

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
Councilwoman answered 2/9, 2009 at 22:37 Comment(1)
Somewhere I saw mentioned that named keys will group like this. ie :unique_index=>:name for both name and domain.Councilwoman
E
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
Exacerbate answered 2/9, 2009 at 22:53 Comment(1)
Actually there already is a key, I just didn't include it in the code snippet.Councilwoman
H
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
Heterogony answered 5/1, 2010 at 1:16 Comment(2)
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.Councilwoman
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: rubydoc.info/github/datamapper/dm-core/master/DataMapper/…. The statements create a multi-column composite unique index.Desired
D
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).

Dawna answered 13/4, 2012 at 0:10 Comment(1)
I've moved away from DataMapper so this may have changed, but at the time I wrote the comment, it was correct.Councilwoman
E
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
Exacerbate answered 2/9, 2009 at 22:53 Comment(1)
Actually there already is a key, I just didn't include it in the code snippet.Councilwoman

© 2022 - 2024 — McMap. All rights reserved.