Mongoid 创建新用户
我正在尝试使用 Ruby on Rails 和 Mongoid Mapper 编写一个示例应用程序。
对于某种测试,我想将 1000 个测试用户写入 MongoDB...
使用下面的代码,Mongoid 无法写入唯一的 uid。在我的 ruby 控制台中,我得到了计数器的正确数字,但没有得到 uid 的正确数字。
有人知道我忘记了什么吗?
class User
include Mongoid::Document
include Mongoid::Timestamps
def self.create_users
(1..1000).each do |f|
user = User.new(uid: f.to_s, first_name: "first_name", last_name: "last_name", e_mail: "e_mail")
user.save!
puts f
puts user.uid
end
end
field :uid, :type => String
field :first_name, :type => String
field :last_name, :type => String
field :e_mail, :type => String
field :messages, :type => String
attr_accessible :first_name, :last_name, :e_mail
validates_presence_of :uid, :first_name, :last_name, :e_mail
validates_uniqueness_of :uid
has_many :messages
end
I'm trying to write an example app using Ruby on Rails and the Mongoid Mapper.
For some kind of Testing I want to write 1000 Testusers into MongoDB...
With the code bolow Mongoid is not able to write unique uid's. In my ruby console i got the right number for the counter but not for the uid.
Does anybody know what I forgot?
class User
include Mongoid::Document
include Mongoid::Timestamps
def self.create_users
(1..1000).each do |f|
user = User.new(uid: f.to_s, first_name: "first_name", last_name: "last_name", e_mail: "e_mail")
user.save!
puts f
puts user.uid
end
end
field :uid, :type => String
field :first_name, :type => String
field :last_name, :type => String
field :e_mail, :type => String
field :messages, :type => String
attr_accessible :first_name, :last_name, :e_mail
validates_presence_of :uid, :first_name, :last_name, :e_mail
validates_uniqueness_of :uid
has_many :messages
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不必在模型中提供字段 uid。 MongoId 为您添加 id 字段并在创建操作期间管理该值。
只需删除字段 :uid, :type =>来自模型的字符串
You don't have to provide the field uid in your models. MongoId add the id field for you and manages the value during the create operation.
Simply remove field :uid, :type => String from model
如果您想使用自己的 ids,您可以将 uid 字段的名称更改为 _id,它应该可以正常工作。但是,默认生成的 mongo _id 将使扩展变得更容易,并且如果您需要该功能,使用它可以消除分片中更困难的方面之一。
如果您想使用默认生成的字段,除非显式覆盖(您已经看到的行为),否则它们会自动包含在内,因此只需删除您的自定义字段即可。
您可以在此处了解有关 ObjectId 的更多信息。
If you want to use your own ids you can change the name of the uid field to _id and it should work just fine. However, the default generated mongo _id will make it easier to scale and using it removes one of the more difficult aspects of sharding if you ever need that feature.
If you want to use the ones that are generated by default, they are included automatically unless overridden explicitly (behavior which you have seen) so just remove your custom field and you should be all set.
You can read more about ObjectIds here.