因此,我在嵌入式文档中遇到了一些用户身份验证问题。我有两个文档,一个嵌入另一个。一个企业有很多成员。模型看起来像这样:
class Member
include Mongoid::Document
field :username, type: String
field :password, type: String
embedded_in :business
validates :username, :presence => true, :uniqueness => true, :length => 5..60
end
class Business
include Mongoid::Document
field :name, type: String
embeds_many :members
end
问题是它没有在每个模型中验证用户名的唯一性。当我在企业中保存一个成员时,我可以保存一千个同名成员。这当然不适用于良好的身份验证系统。我正在使用 Mongoid 2、Rails 3 和 Ruby 1.9
最佳答案
这是使用嵌入式文档时的正常行为,如下所述:MongoID validation
validates_uniqueness_of
Validate that the field is unique in the database: Note that for embedded documents, this will only check that the field is unique within the context of the parent document, not the entire database.
我认为您想尝试在用户名字段中创建一个索引,以确保该集合的所有对象之间的唯一性。像这样:
ensureIndex({username:1},{unique:true});
编辑:如果您希望 Mongo 在存在具有相同索引值的文档时抛出异常,则必须避免 Mongo 执行“即发即弃”模式。这意味着当您对文档执行更新/写入操作时,数据库不会等待响应。
你想传递这个参数:safe:true
。通过这样做,如果由于任何原因无法插入文档,Mongo 应该引发异常。
关于ruby-on-rails - Rails 3 和 Mongoid : Embedded documents validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9356764/