ruby on rails - How to lazy-set Mongoid association -


i have 2 models associated has_one relationship. have callback initializes association. classes (roughly) this:

class user   has_one :relevance, class_name: 'user::relevance', inverse_of: :user, dependent: :destroy   after_create :initialize_relevance    def initialize_relevance     self[:relevance] = user::relevance.new   end    # other garbage *should* irrelevant end  class user::relevance   belongs_to :user, inverse_of: :relevance, index: true    # more other garbage *should* irrelevant end 

sometimes relevance association gets wonked state nil. when happens, want re-initialize relationship when called , return instead of nil. in class user, have this:

def relevance   self[:relevance] = user::relevance.new if self[:relevance].nil?    self[:relevance] end 

except doesn't work , nil still returned. i've tried same update_attribute(user::relevance.new) , self.create_relevance nil seems returned. not sure go here , love ideas. can provide more code or examples if helpful.

additional details:

  • we're using mongoid our database.
  • we don't have other callbacks affect relevance.

mongoid supports autobuilding one-to-one relations. should (no hooks or getter overrides needed).

has_one :relevance,          class_name: 'user::relevance',          inverse_of: :user,          dependent: :destroy,          autobuild: true 

as option name hints, relevance spring life upon access (if nil before access).

also, aware way relevance not persisted, right?

  after_create :initialize_relevance    def initialize_relevance     self[:relevance] = user::relevance.new   end 

so no wonder returns nil later on.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -