我是mongoid的新人,我有两个基本的(我认为)问题。什么是在Mongoid中存储引用数组的最佳方法。这是我需要的简短示例(简单投票):
{
"_id" : ObjectId("postid"),
"title": "Dummy title",
"text": "Dummy text",
"positive_voters": [{"_id": ObjectId("user1id")}, "_id": ObjectId("user2id")],
"negative_voters": [{"_id": ObjectId("user3id")}]
}
它是正确的方式吗?
class Person
include Mongoid::Document
field :title, type: String
field :text, type: String
embeds_many :users, as: :positive_voters
embeds_many :users, as: :negative_voters
end
或者错了?
另外我也不确定,这种情况可能是一个糟糕的文档结构?如果用户已经投票并且不允许用户投票两次,我怎么能优雅地获得?也许我应该使用另一种文件结构?
答案 0 :(得分:5)
您可以选择has_many而不是embeds_many,因为您只想在文档中保存选民的引用,而不是亲自保存整个用户文档
class Person
include Mongoid::Document
field :title, type: String
field :text, type: String
has_many :users, as: :positive_voters
has_many :users, as: :negative_voters
validate :unique_user
def unique_user
return self.positive_voter_ids.include?(new_user.id) || self.negative_voter_ids.include?(new_user.id)
end
end