views:

155

answers:

2

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.

A: 

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.

j.
increment! is not a method in mongo_mapperany other ideas?i tried self.save!user.save! after increment, but it didn't work either
Michael Waxman
If `user.save` didn't work, I don't know what else would :/
j.
thanks for your help j, but i tried that as well, and no such luck. weirdly enough, I tried switching around the method (so that user1 and user2 are reversed), and i still can't get the followers_count to update. as a stop gap solution i'm going to just use user1.update_attributes(:followers_count => user1.followers_count + 1), but that's ugly, and I can't figure out what is wrong with the followers_count
Michael Waxman
+1  A: 

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.

John Nunemaker
hey thanks, that mostly works, but about half of the time a user's friend_count will display an old value... could this be related to indexing, or identity map?
Michael Waxman
if you aren't clearing the identity map it could definitely be related to that. indexing would not have anything to do with it.
John Nunemaker