ruby data mapper, load and object and associated objects

125 Views Asked by At

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)
1

There are 1 best solutions below

4
Eugene On BEST ANSWER

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")