简体   繁体   English

Rails:validates_uniqueness_of 条件未按预期工作

[英]Rails: validates_uniqueness_of with conditions not working as expected

I have a model that uses an 'active' flag to soft-delete items instead of destroying them.我有一个 model,它使用“活动”标志来软删除项目而不是销毁它们。 The model has a 'name' property, which must be unique among active items. model 具有“名称”属性,该属性在活动项目中必须是唯一的。 I was trying to use the conditions modifier with validates_uniqueness_of , but it still seems to be checking for uniqueness across both active and inactive items.我试图将conditions修饰符与validates_uniqueness_of一起使用,但它似乎仍在检查活动项目和非活动项目的唯一性。 What am I doing wrong?我究竟做错了什么?

class Foo < ActiveRecord::Base

  attr_accessible :name, :active
  validates_uniqueness_of :name, conditions: -> { where(active:true) }

end

You can use the scope and if modifiers in conjunction for this: 您可以为此使用scopeif修饰符:

scope :active, where(:active => true)
validates :name, :uniqueness => {:message => 'That name is in use', :if => :active?, :scope => :active}

This will cause only items that are active to trigger the validation, and the validation will consider uniqueness only among items that are active. 这将导致仅活动项目触发验证,并且验证将仅考虑活动项目之间的唯一性。

I have confirmed that this works in Rails 3 and 4. 我已经确认这可以在Rails 3和4中使用。

If the scope differs from the conditions, you can apply the scope within those conditions by adding a conditions key to the uniqueness object: 如果范围不同于条件,则可以通过向唯一性对象添加条件键来在这些条件中应用范围:

scope :active, -> { where(active: true) }

validates :active, uniqueness: {
  scope: :name,
  message: 'name is in use',
  conditions: -> { active }
}

这对我有用:

validates :active, :uniqueness => { :scope => :name, :message => 'name is in use'}, :if => :active

This works for me —这对我有用——

validates_uniqueness_of :asset_id, scope: :source,
                        conditions: -> { where.not(source: :azure) },
                        :allow_nil => true, :allow_blank => true,
                        message: "has already been taken with this source." 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM