不同范围条件下的唯一性验证

时间:2016-02-19 15:36:54

标签: ruby mongodb mongoid

class Game

  field :name, type: String
  field :region, type: String
  field :county, type: String
  field :state, type: String
  field :sport, type: String

  # if sport equals football
    validates :name, presence: true, uniqueness: {scope: [:region, :state]}

 # if sport equals baseball
   validates :name, presence: true, uniqueness: {scope: [:county, :state]}

我们如何才能实现某项运动特有的独特性,但具有地区和州,县和州的范围?

2 个答案:

答案 0 :(得分:1)

也许使用条件:

from progressbar import ProgressBar, Percentage, Bar, ETA
from time import sleep


progress, progress_maxval = 0, 10
pbar = ProgressBar(widgets=['Progress ', Percentage(), Bar(), ' ', ETA(), ],
                   maxval=progress_maxval).start()

for i in xrange(progress_maxval):
    progress += 1
    sleep(1)
    pbar.update(progress)

pbar.finish()

请参阅Rails Guides: Conditional Validation

答案 1 :(得分:0)

您可以使用复合唯一索引强制MongoDB中的唯一性,如下所示:

db.collection.createIndex( { a: 1, b: 1 }, { unique: true } )

The MongoDB Doc