Skip to content

Instantly share code, notes, and snippets.

@astjohn
Created April 13, 2012 00:34
Show Gist options
  • Save astjohn/2372342 to your computer and use it in GitHub Desktop.
Save astjohn/2372342 to your computer and use it in GitHub Desktop.
default_scope is interfering with uniqueness validation in mongoid
class Country
include Mongoid::Document
field :country_code, type: String
field :status, type: String, default: "review"
validates_uniqueness_of :country_code
default_scope where(status: "published")
end
c1 = Country.create!(country_code: "CA", status: "published")
c2 = Country.new(country_code: "CA")
# c2.errors will produce uniqueness validation as intended because c1.status == "published"
c1.update_attribute(:status, "review")
c3 = Country.new(country_code: "CA")
# c3.errors will not include uniqueness validation because c1 is not found during uniqueness validation
# since default scope is included during validation and c1.status == "review"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment