ruby-on-rails - Rails 3 和 Mongoid : Embedded documents validation

标签 ruby-on-rails ruby mongodb mongoid activemodel

因此,我在嵌入式文档中遇到了一些用户身份验证问题。我有两个文档,一个嵌入另一个。一个企业有很多成员。模型看起来像这样:

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/

相关文章:

ruby - 无法从 `sudo bundle install` 恢复

mongodb - Mgo 如何在嵌套数组中查找嵌套文档?

mongodb - 搜索数组信息的总和值 - MongoDB

python - 如果记录不存在,MongoDB 是插入记录的最快方法吗?

ruby-on-rails - unicorn ,无法重启: "rack and Rack::Builder must be available for processing config.ru"

ruby-on-rails - Rails 3 对象#尝试不工作?

ruby-on-rails - Rubygems、Bundler 和 RVM 之间的关系

ruby-on-rails - 遵循 http ://ruby. railstutorial.org/tutorial 时出现 RSpec 错误

html - 如何在每次请求时自动预编译 css.erb 文件

ruby-on-rails - Ruby on Rails 两个模型之间的多重多对多关系