I want to create an after_save method for my rate action. It would divide rating_score/ratings and update the column rating.
class KonkurrancersController &
Not sure why people are upvoting the wrong answer and downvoting the correct answer.
Zakelfassi is right and Christian Fazzini is wrong for Rails 3 and above. If you do #update_attributes in a save callback you go into an endless recursion. You want to do #update_column as per his example.
Try it for yourself and you'll see.
Any update_attribute
in an after_save
callback will cause recursion, in Rails3+.
What should be done is:
after_save :updater
# Awesome Ruby code
# ...
# ...
private
def updater
self.update_column(:column_name, new_value) # This will skip validation gracefully.
end
see this after_save method
@konkurrancer.update_attributes :ratings=>'updated value'
what you want is a callback. You can create an after_save callback on your Konkurrancer model, which triggers after the save() method is called for that model.
For example:
class Konkurrancer < ActiveRecord::Base
after_save :do_foobar
private
def do_foobar
rating_score = self.rating_score
ratings = self.ratings
rating = (rating_score/ratings)
self.update_attributes(:ratings => rating)
end
end
[EDIT] You should use self, since the model you are editing is the model itself. Test it out, and apply necessary logic/implementation.
Have a look at this guide for more info.
Hope that helps!