Mongoid - 具有引用数组的字段

enR*_*Rai 2 ruby ruby-on-rails mongoid

我是mongoid的新人,我有两个基本的(我认为)问题.什么是在Mongoid中存储引用数组的最佳方法.这是我需要的简短示例(简单投票):

{
  "_id" : ObjectId("postid"),
  "title": "Dummy title",
  "text": "Dummy text",
  "positive_voters": [{"_id": ObjectId("user1id")}, "_id": ObjectId("user2id")],
  "negative_voters": [{"_id": ObjectId("user3id")}]
}
Run Code Online (Sandbox Code Playgroud)

它是正确的方式?

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
Run Code Online (Sandbox Code Playgroud)

还是错了?

我也不确定,这种情况可能是一个糟糕的文档结构?如果用户已经投票并且不允许用户投票两次,我怎么能优雅地获得?也许我应该使用另一种文件结构?

abh*_*has 5

而不是embeds_many你可以去has_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
Run Code Online (Sandbox Code Playgroud)