我必须建模:Tag
和TagNumeric
每个category
字段
我不能创建具有相同类别的不同类型的标签。我该如何验证?
编辑:
我忘了提及
TagNumeric<标签
class Tag
include Mongoid::Document
validates_presence_of :type, :value
field :category, type: String
field :value, type: String
field :color, type: String
validates :value, :presence => true, :uniqueness => {:scope => :category}
class TagNumeric < Tag
field :value, type: Integer
it 'its category should be unique within the Tag class type' do
Tag.create(category: 'Movie', value: 'Avatar')
TagNumeric.create(category: 'Movie', value: 'Iron man').should_not be_valid
end
答案 0 :(得分:1)
如果有人遇到同样的问题我是如何解决它的
validate :uniqueness_within_category
def uniqueness_within_category
first_category_type = (Tag.find_by(category: self.category).nil?)? 'none' : Tag.find_by(category: self.category)._type
if first_category_type == 'none'
#It doesnt exist then should be allowed
return
end
#If it exists within another class type then shouldnt be allowed
if self._type != first_category_type
errors.add(:category, 'Must be unique within tag type')
end
end
测试于下午6:22开始......
1个例子,0个失败,1个传递