Reputation: 689
I have simple application on rails with Mongodb(Mondoid mapper). Scaffold posts
, and I trying to implement rating functional. Post
has next structure:
> class Post
include Mongoid::Document
include Mongoid::Timestamps
field :title, type: String
field :description, type: String
field :rank, type: Integer, default: "0"
field :voter_up, type: Array, default: []
field :voter_down, type: Array, default: []
As you can see there are two field voter_up
, _down
. It's to add users, depending on how they voted. self.voter_up << user.id
, or self.voter_down << user.id
. In database it looks like:
"voter_up" : [
ObjectId("4ee08b6e405f3d0a29000005"),
ObjectId("4ee0aaff405f3d0a2900003a")
]
And if user changed his mind and wants to vote contrary. For example in first time user voted UP. And then voted DOWN. In this situation I need to delete this user from array voter_up
and add to voter_down
. From rails console it works array.delete(object)
, but if I try that self.voter_up.delete(user.id)
in model function - nothing happens. Why?
Upvotes: 2
Views: 1565
Reputation: 85
self.voter_up << "#{user.id}", or self.voter_down << "#{user.id}" I think this will work, have a try
Upvotes: 0
Reputation: 65887
I am afraid that both of your console and modal would work. Because the delete here you are using is a ruby array method not the mongoids. So You need to call save after delete to push the changed array to server.
self.voter_up.delete(user.id)
self.save
Upvotes: 3