【问题标题】:uniqueness validation on different scope conditions不同范围条件下的唯一性验证
【发布时间】:2016-02-19 15:36:54
【问题描述】:
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]}

我们如何才能实现特定于某项运动的名称的唯一性,但具有地区和州或县和州的范围?

【问题讨论】:

  • 我不明白为什么这被否决了?

标签: ruby mongodb mongoid


【解决方案1】:

也许使用条件:

validates :name, presence: true
validates :name, uniqueness: { scope: [:region, :state] },
                 if: Proc.new { |g| g.sport == 'football' }
validates :name, uniqueness: { scope: [:county, :state] },
                 if: Proc.new { |g| g.sport == 'baseball' }

Rails Guides: Conditional Validation

【讨论】:

    【解决方案2】:

    您可以使用这样的复合唯一索引在 MongoDB 中强制执行唯一性:

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

    The MongoDB Doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多