Mongoid 自定义 setter/getter 和 super
我正在尝试修改属性 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,你所做的根本不属于用户模型。我将在 EmailAccount 模型中创建另一个方法,并将其与 after_save 回调挂钩。
另一种方法是使用观察者 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.
Another way is to use observers http://mongoid.org/docs/callbacks/observers.html
如果它是嵌入式文档,您可以执行以下操作:
我已在控制台中尝试过它,但没有尝试保存并检索它。如果父级是新记录,则保存应该没有问题,否则您可能必须研究如何在嵌入文档上调用保存。
If its an embedded document you can do something on the lines of:
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.