0

I have a User model that has_many :comments and a Comment model that belongs_to :user.

I have want to gather comment.ratings to set user.rating so I have an after_save method in my Comment model that I call. However this never gets called.

Here is the method:

def update_user_rating
  user = User.find(self.is_about)
  user.trip_rating = (Comment.find_all_by_is_about(self.is_about).collect { |comment| comment.rating }.sum) / 
    Comment.find_all_by_is_about(self.is_about).count
end

I checked the ruby code and it works on the console, so I assume its not the ruby code.

Yes I do have after_save :update_user_rating in the model as well.

I am trying to understand what I am doing wrong?

EDIT: Based on the debugger I saw that the first part of the user.trip_rating= is never executing. Meaning I tried to do next on that line but it never went through so I am assuming that line is the problem. However checking in rails console again, I saw that it works there. I don't understand!

SOLVED: Here is how I solved the problem although I don't like it. I removed the after_save callback and added a method to the user model to calculate its own ratings, and called it in the controller.

eytanfb
  • 443
  • 4
  • 17
  • i guess you are not saving the user object. Type at the end `user.save` – Zippie Apr 11 '13 at 16:01
  • I added it but still nothing has changed. it made sense though thanks. – eytanfb Apr 11 '13 at 16:14
  • can you try `user.save!` and if there is a problem saving it it will error it out – Zippie Apr 11 '13 at 16:18
  • @Zippie wouldn't call `user.save` inside the `update_user_rating` method cause infinite recursion since that save will call another `update_user_rating`? – Huy Apr 11 '13 at 16:41
  • it's not a infinite recursion since it's a callback from `comments` not `users` – Zippie Apr 11 '13 at 16:42
  • user.save! did stop the comment from saving so I am assuming there is a problem but I couldn't figure out where. I haven't checked the development.log, is it possible I can see it there? – eytanfb Apr 12 '13 at 16:32

1 Answers1

0

Maybe your update_user_rating is being called, but some line in the method is failing.

Try user = User.find(self.user_id) or user = User.find_by_is_about(self.is_about)

Huy
  • 10,806
  • 13
  • 55
  • 99
  • 1
    Probably should be `user = User.find(self.user_id)`, although i don't know what `self.is_about` means nor contains – Zippie Apr 11 '13 at 16:48
  • Ahh, I missed the part where this is a callback from comments and not users – Huy Apr 11 '13 at 16:49
  • user_id is the owner of a comment whereas is_about is which user it is about – eytanfb Apr 13 '13 at 07:27