Don't reload :default values every time the object is loaded #402

matthiassiegel opened this Issue Apr 5, 2012 · 4 comments


None yet

5 participants


Currently when you define :default values on keys, these seem to get reloaded every time the object is loaded. This turns into a lof of repeated database queries when some of these defaults reference other models, e.g.

key :stuff, String, :default => lambda { Stuff.first._id }

Here is a full example:

require 'mongo_mapper'

MongoMapper.database = 'test'

class Stuff
  include MongoMapper::Document

  key :some_key, String, :default => lambda { Stuff.some_function }

  def self.some_function
    puts "some_function called"

s =

I think the desired behaviour is probably to ignore attribute defaults once they have been set and persisted. But I'm not sure about the case when you later set an attribute to nil again.


Thanks for the report. Fixing this will make stuff like sequential id's much cleaner to implement.

Related issues: #320 #332 #393 #269


We're hitting this problem as well.

Would you welcome a pull request that changes the life-cycle of default values? Ideally, they should only be merged with the attributes hash on the initialization of the model. Default values should not be re-set after initiallization.


Yeah I'm open to it. Clean with tests is about all I care about.


I've got a pull request for this work here: #449

@cheald cheald added a commit that referenced this issue Jul 5, 2013
@cheald cheald Add specs to cover #402, #403, #320 4f829f0
@cheald cheald closed this Jul 5, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment