2

Im newbee in mongoid and I have two basic (I think) questions. Whats best way to store array of references in Mongoid. Here is a short example what I need (simple voting):

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

And its a right way?

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

Or its wrong?

Also Im not sure, maybe its a bad document structure for this situation? How can i gracefully get if user already voted and dont allow users vote twice? Maybe I should use another structure of document?

enRai
  • 671
  • 6
  • 12

1 Answers1

5

Rather than embeds_many you can go for has_many because you just want to save the reference of voters in the document rather than saving whole user document in person

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
abhas
  • 5,193
  • 1
  • 32
  • 56
  • ok, thats right. but with this mapping one user can vote twice. one negative and one positive. right? but needed just one vote (negative or positive) per post. – enRai Jun 03 '12 at 08:50