1

How do I load an object and all associated objects? I'm asking because lazy loading (I think it's lazy loading) is causing me problems. Whilst this is a slow thing to do, it's fine as this script will only run once every 10mins.

is there something like:

Model_Object.all(load_all_now: true)
Thermatix
  • 2,757
  • 21
  • 51

1 Answers1

1

Unfortunately, there is not a good way to do that. The easiest solution is to actually query the individual records, which is of course even slower than loading all of the attributes at once with something like:

objects = ModelObject.all.map { |o| ModelObject.get(o.id) }

Slightly more complex, you could overload DataMapper::Resource with a method like this:

  def from_sql(sql, *bind_values)
    self.repository.adapter.select(sql, *bind_values).map(&:as_json).map do |h|
      if h.is_a?(Hash)
        self.new(h)
      else
        self.new(id: h)
      end.tap do |record|
        record.persistence_state = DataMapper::Resource::PersistenceState::Clean.new(record)
      end
    end
  end

and then pass in something like this:

properties = ModelObject.properties.map(&:field)
objects = ModelObject.from_sql("SELECT #{properties.join(", ")} FROM table_name")
Eugene
  • 4,829
  • 1
  • 24
  • 49
  • Why is there no way to force load all objects? – Thermatix Jul 24 '17 at 13:06
  • Wish I could give you an answer to that. DataMapper is an old project that hasn't really been maintained in a number of years. ActiveRecord is leaps and bounds more advanced and developer friendly, but some of us are still bound to using DM. The method I gave you in my answer was added to the application I work on to get around some of the shortcomings of DM, but there are always more. – Eugene Jul 24 '17 at 13:34
  • I see, well thanks, guess next time I'll just have to integrate active record. – Thermatix Jul 24 '17 at 16:41
  • Just to clarify, objects contains all instances of ModelObject + associated objects? – Thermatix Jul 24 '17 at 17:12