Mongoid 自定义 setter/getter 和 super

发布于 2024-11-24 02:49:20 字数 852 浏览 0 评论 0原文

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

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

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

除了它不是子类之外,会产生

NoMethodError: super: no superclass method

有想法吗?

编辑:

你会如何做一个吸气剂,比如

class User
    include Mongoid::Document

    embeds_one :email_address

    def email_address
        super || "[email protected]"
    end
end

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

Ideas?

EDIT:

How would you do a getter, like

class User
    include Mongoid::Document

    embeds_one :email_address

    def email_address
        super || "[email protected]"
    end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤 2024-12-01 02:49:20

在我看来,你所做的根本不属于用户模型。我将在 EmailAccount 模型中创建另一个方法,并将其与 after_save 回调挂钩。

class EmailAccount
  include Mongoid::Document

  embedded_in :user

  after_save :do_something

  def do_something
    puts "email account updated!"
    do_actual_something
  end
end

另一种方法是使用观察者 http://mongoid.org/docs/callbacks/observers.html

In my opinion what you're doing doesn't belong to User model at all. I'd create another method in EmailAccount model and hook it with after_save callback.

class EmailAccount
  include Mongoid::Document

  embedded_in :user

  after_save :do_something

  def do_something
    puts "email account updated!"
    do_actual_something
  end
end

Another way is to use observers http://mongoid.org/docs/callbacks/observers.html

冷…雨湿花 2024-12-01 02:49:20

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

def doc=(_doc)
  self.build_doc(_doc.attributes)
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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文