Question

I'm using mongo_mapper 0.7.5 and rails 2.3.8, and I have an instance method that works in my console, but not in the controller of my actual app. I have no idea why this is.

#controller
if @friendship.save
   user1.add_friend(user2)
...

#model
...
key :friends_count, Integer, :default => 0
key :followers_count, Integer, :default => 0

def add_friend(user)
   ...
   self.increment(:friends_count => 1)
   user.increment(:followers_count => 1)
   true
end

And this works in the console, but in the controller it does not change the follower count, only the friends count. What gives? The only thing I can even think of is that the way that I'm passing the user in is the problem, but I'm not sure how to fix it.

Was it helpful?

Solution

The issue is most likely that the increment has happened but you have not reloaded your model with the data from the database. Increment fires the db query but does not update the instance. Try @friendship.reload and user.reload after the add_user call in your controller.

OTHER TIPS

Looks like you're not saving the user, so try increment! instead. This method will save the user and return true if the record could be saved.

Edit

I found another way of doing that (hopefully the right one):

User.increment(user.id, :followers_count => 1)

I have not tested this code! But I hope it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top