Datamapper JSON 哈希未更新
在带有 DataMapper 和 dm-types 的 Ruby/Sinatra 中,在模型挂钩中我有这样的代码块:
self.parent.meta[:post_count] += 1
self.parent.save
不幸的是,这不起作用——元(JSON 类型列)不会更新。请帮忙?
In Ruby/Sinatra with DataMapper and dm-types, in a model hook I have this block of code:
self.parent.meta[:post_count] += 1
self.parent.save
Unfortunately, that doesn't work -- the meta, which is a JSON type column, does not get updated. Help, please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您通过其自己的 API(在您的情况下为 #[])修改复杂的属性值(例如 JSON)时,DM 中的脏跟踪系统不幸被绕过,这意味着您的资源不会被标记为脏。这不是一个需要解决的小问题,但迟早会完成。
目前,作为一种解决方法,您可以覆盖整个元属性值并增加 post_count,例如:
self.parent.meta =parent.meta.merge("post_count" =>parent.meta.fetch("post_count" , 0)+1)
我知道这看起来不太好,但现在没有其他方法可以做到这一点。您可以将该代码封装在像
increment_post_count
这样的方法中以使其正确。另外,请注意您应该使用字符串键而不是符号。
When you modify a complex property value, such as JSON, via its own API (#[] in your case) the dirty tracking system in DM is unfortunately bypassed which means your resource won't be marked as dirty. It's not a trivial issue to solve but sooner or later it will be done.
For now as a workaround you could override entire meta property value and increment the post_count, for instance:
self.parent.meta = parent.meta.merge("post_count" => parent.meta.fetch("post_count", 0)+1)
I understand it doesn't look nice but there's no other way to do that now. You could encapsulate that code in a method like
increment_post_count
to make it right.Also, please notice that you should use string keys rather than symbols.