本文介绍了通过“<<"分配嵌入项目时触发在嵌入项目上的after_save在蒙古族吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以在Mongoid映射器中的Embedded_in对象上触发after_save回调.

I was wondering if there was a way to trigger the after_save callback on an embedded_in object in Mongoid mapper.

示例:

i = Image.new(:file => file)
user.images << i
# => i.after_save should be triggered here

我知道,如果我在单词后调用i.save,它将触发,但是在整个代码中都很难记住这样做.

I'm aware that if I call i.save after words, it will fire, however really hard to remember to do that throughout my code.

此外,不能选择调用user.images.create(:file => file),因为我进行了检查以确保同一文件没有上传两次.

Also, calling user.images.create(:file => file) is not an option, because I do a check to make sure the same file isn't uploaded twice.

推荐答案

唯一真正的解决方案是在嵌入式文档上调用save.这是一种自动完成此操作的方法:

The only real solution is to call save on the embedded document. Here's a way to have that done automatically:

class User
  references_many :images do
    def <<(new_elm)
      returner = super
      new_elm.save
      returner
    end
  end
end

更多信息在这里:

https://github.com/mongoid/mongoid/issues/173

这篇关于通过“&lt;&lt;"分配嵌入项目时触发在嵌入项目上的after_save在蒙古族吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 03:20