Rails how to update a column after saving?

前端 未结 5 2083
栀梦
栀梦 2020-12-15 08:09

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 &         


        
相关标签:
5条回答
  • 2020-12-15 08:43

    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.

    0 讨论(0)
  • 2020-12-15 08:44

    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
    
    0 讨论(0)
  • 2020-12-15 08:49

    see this after_save method

    0 讨论(0)
  • 2020-12-15 08:53
      @konkurrancer.update_attributes :ratings=>'updated value'
    
    0 讨论(0)
  • 2020-12-15 08:56

    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!

    0 讨论(0)
提交回复
热议问题