保存后什么时候更新记录? [英] when to update record after save?

查看:35
本文介绍了保存后什么时候更新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用回形针将文件附加到我的模型上.我想要做的是,在保存模型并将文件写入磁盘后,我需要更新模型中关于文件的另一个属性(CRC).由于回形针直到调用 .save 之后才会将文件写入磁盘,因此我的第一个想法是使用 after_save 回调.当我这样做时,我收到SystemStackError(堆栈级别太深):"错误.然后我尝试做一个 after_commit 回调,它似乎工作得更好一些.例如,如果我只是将我的 crc 分配给:

I am using paperclip to attach files to a Model of mine. What I would like to do is, after the model has been saved and the file written to disk, I need to then update another attribute in my model about the file (a CRC). Since paperclip does not write the file to disk until after the .save has been called, my first thought was to use the after_save callback. When I do this, I get a "SystemStackError (stack level too deep):" error. Then I tried to do a after_commit callback which seems to be working a little better. For example, if I simply assign my crc with:

self.crc = "TEST"
self.save

这有效.但是,如果我尝试完成真正的任务,请使用以下方法:

This works. However, If I try to do my real assignment, with this:

self.crc = "0x" + IO.read(self.patchfile.path, 4, 0x20).unpack("H8").join
self.save

WEBrick 中止:

WEBrick aborts with:

/usr/local/rvm/rubies/ruby-1.9.2-p290/lib/libruby.so.1.9(+0x180048) [0x290048]
/usr/local/rvm/rubies/ruby-1.9.2-p290/lib/libruby.so.1.9(rb_yield+0x56) [0x294c46]

[NOTE]
You may have encountered a bug in the Ruby interpreter or extension libraries.
Bug reports are welcome.
For details: http://www.ruby-lang.org/bugreport.html

Aborted

所以我认为我做错了...

So I am thinking I am doing this wrong...

推荐答案

您在 after_save 回调中,并且正在调用 save.这将再次触发您的回调,这就是您的无限循环堆栈级别太深"错误的来源.

You're inside of an after_save callback, and you're calling save. That's going to trigger your callback again, which is where your infinite loop "stack level too deep" error is coming from.

考虑使用从回调中排队的 DelayedJob.让后台任务处理分配 CRC 的工作.但是,您仍然会发生无限循环,但这次是无限循环的排队作业.

Consider using a DelayedJob which you queue from your callback. Let a background task handle the work of assigning your CRC. However, you'll still have an infinite loop happening, but this time an infinite loop of queued jobs.

查看:如何避免运行 ActiveRecord 回调? 有关在特定条件下跳过回调的提示.

Take a look at: How can I avoid running ActiveRecord callbacks? for tips on skipping your callbacks under certain conditions.

您可能还想编写自己的 Paperclip 后处理器.查看自述文件中有关后处理"和自定义附件处理器"的部分,并深入研究代码以了解现有处理器的运行方式.

You might also want to write your own Paperclip post processor. Take a look at the sections on "Post Processing" and "Custom Attachment Processors" in the readme, and dig through the code to see how the existing processors operate.

https://github.com/thoughtbot/paperclip

这篇关于保存后什么时候更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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