轨。更新模型属性上保存 [英] Rails. Update model attributes on save

查看:136
本文介绍了轨。更新模型属性上保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以为这是一件容易的事,但是我一直坚持这个问题有点:

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

和web服务器笋回来的消息的ActiveRecord :: StatementInvalid(SystemStackError:堆栈层次过深:INSERT INTO版本

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

这基本上告诉我,有一种保存到模型中的infite循环, after_save的,然后我们再保存模型......这些进入的另一个循环保存模式

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

推荐答案

更改code到以下

before_save :calculate_and_save_budget_contingency

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

原因是 - 如果你运行在保存 after_save的您在无限循环结束:保存after_save的回调函数调用,调用保存它调用after_save的,这..

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.

这篇关于轨。更新模型属性上保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆