Jackie Chan
Jackie Chan

Reputation: 2662

Rails. Update model attributes on save

Thought it's an easy task however I have stuck a little bit with this issue:

Would like to update one of the attributes of the model whenever it's saved, thus having a callback in the model:

after_save :calculate_and_save_budget_contingency

def calculate_and_save_budget_contingency
  self.total_contingency = self.budget_contingency + self.risk_contingency
  self.save
  # => this doesn't work as well.... self.update_attribute :budget_contingency, (self.budget_accuracy * self.budget_estimate) / 1
end

And the webserver shoots back with the message ActiveRecord::StatementInvalid (SystemStackError: stack level too deep: INSERT INTO "versions"

Which basically tells me that there is an infite loop of save to the model, after_save and then we save the model again... which goes into another loop of saving the model

Just stuck at this point of time on this model attribute calculation. If anyone has encountered this issue, and has a nice nifty/rails solution, please shoot me a message below, thanks

Upvotes: 3

Views: 1463

Answers (2)

Mike Szyndel
Mike Szyndel

Reputation: 10593

Change your code to following

before_save :calculate_and_save_budget_contingency

def calculate_and_save_budget_contingency
  self.total_contingency = self.budget_contingency + self.risk_contingency
end

Reason for that is - if you run save in after_save you end up in infinite loop: a save calls after_save callback, which calls save which calls after_save, which...

In general it's wise you use after save only for changing associated models, etc.

Upvotes: 3

bratsche
bratsche

Reputation: 2674

Try before_save or before_validation, but don't include the .save

Upvotes: 1

Related Questions