问题
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 || "myself@gmail.com"
end
end
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/6699503/mongoid-custom-setters-getters-and-super