我是 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
还是错了?
我也不确定,对于这种情况来说,也许它的文档结构不好?如果用户已经投票并且不允许用户投票两次,我该如何优雅地获得?也许我应该使用另一种文档结构?
最佳答案
您可以选择 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
关于ruby-on-rails - Mongoid - 具有引用数组的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10863474/