mongoid/mongoid — Issue #1656: Uniqueness constraint violated when attribute doesn't change but scope changes.
Author: priyaaank
Created: 2012-01-30 17:30:55+00:00
State: open

class Folder
include Mongoid::Document
field :name, :type => String
has_many :folder_items
end

class FolderItem
include Mongoid::Document
belongs_to :folder
field :name, :type => String
validates :name, :uniqueness => {:scope => :folder_id}
end

personal_folder.folder_items << FolderItem.new(:name => "non-unique")
public_folder.folder_items << FolderItem.new(:name => "non-unique")

public_folder.folder_items.first.update_attributes(:folder_id => personal_folder.id)

Last statement should fail, but it doesn't. It's because as per the #1576 we skip db call if the attribute value hasn't changed. However this skips the fact that value may remain the same but scope may change; hence the failure.