不同范围条件下的唯一性验证
uniqueness validation on different scope conditions
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]}
我们如何才能实现特定于一项运动但具有区域&州或县&州范围的名称的唯一性?
可能使用条件:
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' }
您可以使用复合唯一索引在 MongoDB 中强制执行唯一性,如下所示:
db.collection.createIndex( { a: 1, b: 1 }, { unique: true } )
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]}
我们如何才能实现特定于一项运动但具有区域&州或县&州范围的名称的唯一性?
可能使用条件:
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' }
您可以使用复合唯一索引在 MongoDB 中强制执行唯一性,如下所示:
db.collection.createIndex( { a: 1, b: 1 }, { unique: true } )