2010-10-28 59 views
3

我希望能够将条目放入我的数据库中,制造商将被多次表示,但不是制造商和型号的相同组合。 所以“索尼(制造商),电视(模型)”是好的“索尼(制造商),其他(模型)”,但第三项“索尼(制造商),电视(型号)”是不好的,因为制造商和模型不是唯一的。我尝试了:key => true验证,但它似乎没有工作。我不能做像validates_uniqueness_of :manufacturer AND :model这样的事情。你是怎么做到的?验证DataMapper中组合字段的唯一性

class Tvs 
    include DataMapper::Resource 

    property :id,   Serial 
    property :manufacturer, String, :key => true 
    property :model,  String, :key => true 

    validates_uniqueness_of : 
end 

回答

5

实际上,你可以一起去:

​​

这也将让您在数据库中唯一索引。

+0

很酷。谢谢。所以这会给我一个名为manufacturer_model的数据库中的新列或什么? – schwift 2010-11-07 18:45:54

+0

不是列,而是unique_index。称为'unique_tvs_manufacturer_model'或类似的东西,并在两列。 – namelessjon 2010-11-07 19:16:57

0

没关系。 看来这做的工作:

class Tvs 
    include DataMapper::Resource 

    property :id,   Serial 
    property :manufacturer, String, :unique_index => true 
    property :model,  String, :unique_index => true 

    validates_uniqueness_of :model, :scope => :manufacturer 
end 
0
class Tvs 
    include DataMapper::Resource 

    property :id,   Serial 
    property :manufacturer, String, :unique_index => :manufacturer_model 
    property :model,  String, :unique_index => :manufacturer_model 

    validates_is_unique :model, :scope => :manufacturer 
end 

我需要修改示例以使用“validates_is_unique”来使其工作。

0

如果您删除property :id Serial这一行,最终将出现一个组合键(制造商,型号),不允许特定制造商使用重复的型号。