2009-09-02 59 views
8

在Datamapper中,如何指定兩個字段的組合必須是唯一的。例如,類別在域中必須具有唯一名稱:datamapper多字段唯一索引

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

    belongs_to :domain 
end 
+0

我看到的某處提到,指定的按鍵會像這樣分組。即:unique_index =>:名稱和域名。 – 2009-09-03 18:52:15

回答

1

您是否嘗試將兩個屬性都定義爲鍵?不知道我已經嘗試過,但這樣他們應該成爲一個複合關鍵。

property :name, String, :key => true  
property :category, Integer, :key => true 
+0

其實已經有一個關鍵,我只是沒有包含在代碼片段中。 – 2009-09-03 18:50:54

16

你必須創建兩個屬性唯一索引:

class Category 
    include DataMapper::Resource 

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

    belongs_to :domain 
end 
+0

這是不正確的,因爲它要求名稱和域在整個表中都是唯一的。我問的是如何使集合(:name,:domain)獨一無二。 – 2010-03-24 00:06:59

+0

:unique_index =>:named_u正是我所需要的!謝謝! – 2012-08-30 14:25:49

+0

事實上,儘管':u'符號可能更清晰 - 例如':index_on_name_and_domain_id' - 它確實是正確的。請參閱DataMapper屬性文檔頁面上的索引部分:http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Property。這些語句創建一個多列組合唯一索引。 – 2013-02-18 20:06:46

2

其實,約翰,Joschi的答案是正確的:使用命名的:unique_index值並創建一個多列索引;閱讀這些散列火箭的右側是非常重要的(即,如果它剛好是true,那麼你會是對的)。

+0

我已經離開DataMapper,所以這可能已經改變了,但是在我寫評論的時候,這是正確的。 – 2012-04-13 04:58:02