I have a rail application with 3 models.
class User < ActiveRecord::Base
has_many :ratings
end
class Movie < ActiveRecord::Base
has_many :reviews
accepts_nested_attributes_for :reviews
end
class Review < ActiveRecord::Base
belongs_to :movie
belongs_to :user
after_create :update_movie_rating
def update_movie_rating
movie.update_average_rating
end
end
I'm trying to update the average rating of movie after creating each reviews.
Here is the methods I use in movie model.
def update_average_rating(review=nil)
s = self.reviews.sum(:rating)
c = self.reviews.count
self.update_attribute(:average_rating, c == 0 ? 0.0 : s / c.to_f)
end
This method is using with after_create
callback in the review model.
But I get error like this when I deploy to heroku. I can't make post
to the the application which is deployed on heroku. What will be the reason behind it?
I get it right while trying to update it with admin panel (active admin).
NoMethodError (undefined method `update_average_rating' for nil:NilClass):
2015-06-08T20:09:06.297312+00:00 app[web.1]: app/models/review.rb:6:in `update_movie_rating'
2015-06-08T20:09:06.297314+00:00 app[web.1]: app/controllers/reviews_controller.rb:36:in `block in create'
2015-06-08T20:09:06.297315+00:00 app[web.1]: app/controllers/reviews_controller.rb:35:in `create'
How can I solve it?