[ACCEPTED]-Rails how to update a column after saving?-ruby-on-rails-3

Accepted answer
Score: 80

Any update_attribute in an after_save callback will cause recursion, in 1 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
Score: 12

Not sure why people are upvoting the wrong 7 answer and downvoting the correct answer.

Zakelfassi 6 is right and Christian Fazzini is wrong 5 for Rails 3 and above. If you do #update_attributes 4 in a save callback you go into an endless 3 recursion. You want to do #update_column 2 as per his example.

Try it for yourself and 1 you'll see.

Score: 8

what you want is a callback. You can create 7 an after_save callback on your Konkurrancer 6 model, which triggers after the save() method 5 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 4 should use self, since the model you are editing 3 is the model itself. Test it out, and apply 2 necessary logic/implementation.

Have a look 1 at this guide for more info.

Hope that helps!

Score: 0
  @konkurrancer.update_attributes :ratings=>'updated value'

0

Score: 0

see this after_save method

0

Score: 0

Many of the answers on this post might have 7 been correct but are out of date now. The 6 Rails docs suggests assigning values directly (self.attribute = 'value') instead 5 of updating or saving attributes (update(attribute: 'value') in callbacks.

Good

after_save :do_foobar

private

def do_foobar
  self.attribute = "value"
end

Bad (.update_column)

Safe 4 because it will prevent additional callbacks 3 from being triggered but not suggested as 2 it can have unintended side effects.

after_save :do_foobar

private

def do_foobar
  update_column(:attribute, "value")
end

Worse (.update)

Can 1 trigger subsequent callbacks infinitely.

after_save :do_foobar

private

def do_foobar
  update(attribute: "value")
end

More Related questions