Mongoid自定义安装程序/吸气剂和超级 [英] Mongoid custom setters / getters and super

查看:74
本文介绍了Mongoid自定义安装程序/吸气剂和超级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图修改属性Mongoid模型上的设置器,但与ActiveRecord不同,我无法调用super来让Mongoid实际设置属性,因为该模型使用的是include Mongoid::Document而不是ActiveRecord::Base的子类.

I'm trying to modify a setter on an attribute Mongoid model, but unlike ActiveRecord, I cannot call super to have Mongoid actually set the attribute, as the model is using include Mongoid::Document rather than a subclass of ActiveRecord::Base.

我希望能够做这样的事情.

I want to be able to do something like this.

class User
    include Mongoid::Document

    embeds_one :email_account

    def email_account=(_email_account)
        ret = super
        puts "email account updated!"
        do_something
        ret
    end
end

除了不是它的子类,它会产生

except, as its not a subclass, yields

NoMethodError: super: no superclass method

想法?

您将如何做吸气剂,如

class User
    include Mongoid::Document

    embeds_one :email_address

    def email_address
        super || "myself@gmail.com"
    end
end

推荐答案

如果它是嵌入式文档,则可以执行以下操作:

If its an embedded document you can do something on the lines of:

def doc=(_doc)
  self.build_doc(_doc.attributes)
end

我已经在控制台中尝试过了,但是没有尝试保存并取回它.如果父项是新记录,则保存应该没有问题,否则,您可能必须研究如何在嵌入式文档中调用保存.

I have tried it in console but didn't tried saving and retrieving it back. If parent is a new record save should be trouble-less, otherwise you might have to look into how to call save on embedded document.

这篇关于Mongoid自定义安装程序/吸气剂和超级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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