使用 rubyist-aasm 保留转换时的状态列(充当状态机)
使用 aasm 在转换时将对象状态持久保存到数据库的最佳方法是什么? 我原以为这会自动发生,但事实似乎并非如此。
(编辑:当我手动保存对象时,状态列确实会更新。但是在转换时不会完成保存。)
我找不到这个插件的太多有用的文档,所以如果您有一个替代有限的建议具有更好文档的状态机实现,这也可能有所帮助。
What is the best way to persist the object's state to the database on a transition using aasm? I had thought that this would happen automatically but this doesn't seem to be the case.
(Edit: when I manually save the object, the state column does get updated. But a save isn't done on transitions.)
I can't find much useful documentation for this plugin, so if you have a suggestion for an alternative finite state machine implementation with better documentation, that might help as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您调用 bang! 形式的转换事件方法,状态将持续存在。 例如,假设您有一个具有以下事件的对象:
调用
book.close
会将状态设置为关闭
,但不会自动保存。 调用book.close!
将设置状态*并*自动保存 AR 对象。If you call the bang! form of the transition event method, the state will persist. For example, say you have an object with the following event:
Calling
book.close
will set the state toclosed
, but will not automatically save. Callingbook.close!
will set the state *and* automatically save the AR object.正如 Colin 所建议的,AASM 将为您保留您的更改。 马库斯所说的完全错误,除了最新版本的宝石有一个错误之外。
在 lib/persistence/active_record_persistence.rb 的第 180 行(您可以通过运行 gem:unpack 获得它),您应该看到注释,其中指出:
但是,在代码中,它实际上调用了 save!
当底层模型验证失败时,就会出现该错误,因为 save 方法默认不会绕过验证。 一个快速解决方法是这样做:
现在,转换确实将新状态保存到数据库中。
As Colin suggests, AASM will persist your changes for you. What Markus has said is flat out incorrect, except for the fact that the latest version of the gem has a bug.
On line 180 of lib/persistence/active_record_persistence.rb (you can get this by running gem:unpack), you should see the comment, which states:
However, in the code, it actually calls save instead!
The bug occurs when the underlying model fails validation, because the save method does not bypass validation by default. A quick fix would be to do this instead:
Now, transitions do indeed save the new state to the database.
我相信 AASM 会在转换后保留对象的状态。 请参阅 aasm/lib/persistence/active_record_persistence.rb 中的第 180-189 行
I believe AASM will persist the state of the object after transition. See lines 180-189 in aasm/lib/persistence/active_record_persistence.rb
我认为如果这是你想要的效果,你必须在过渡中保存。 根据设计,ActiveRecord(aasm 位于其之上)不会自动保存记录。
您可以在
I think you have to save in the transition if that's the effect you want. ActiveRecord (which aasm is sitting on top of) doesn't autosave records, by design.
You can do the saving in a callback if you want (and it sounds like you do).