Mongoid custom setters / getters and super

早过忘川 提交于 2019-12-10 17:45:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!