开发者

MongoMapper, Rails, Increment Works in Console but not Controller

开发者 https://www.devze.com 2023-01-03 16:27 出处:网络
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.

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消