user1130176
user1130176

Reputation: 1864

mongoid equivalent of loaded?

In a Rails app, using ActiveRecord with mysql, you can check to see if an association has been loaded:

class A
    belongs_to :b

a = A.find(...
a.b.loaded? # returns whether the associated object has been loaded

Is there an equivalent in mongoid? ._loaded? used to work but no longer does.

UPDATE - adding example

class A
    include Mongoid::Document
end

class B
    include Mongoid::Document
    belongs_to :a
end

a = A.new
b = B.new
b.a = a
b.a._loaded?

returns:

ArgumentError (wrong number of arguments (given 0, expected 1))

Upvotes: 0

Views: 167

Answers (3)

don_Bigote
don_Bigote

Reputation: 947

You can test if includes(:your_association) has been added to the criteria like this:

inclusions = Criteria.inclusions.map(&:class_name)
inclusions.include?('YourAssociation)

For example:

Children.all.include(:parent).inclusions
=> [<Mongoid::Association::Referenced::BelongsTo:0x00007fce08c76040
  @class_name="Parent", ...]

Children.all.inclusions
=> []

Upvotes: 0

Brilnius
Brilnius

Reputation: 29

Maybe the purpose was not the same. Now (Mongoid 7.0) _loaded?() is a private method, and in my case it always returns true.

The best I could find is ivar(): it returns the object if already loaded, or false if not loaded.

I'm not sure if this is a reliable solution. It depends on further availability of ivar() and the way objects are stored as instance variables.

> b = B.find('xxx')
  => (db request for "b")
> b.ivar('a')
  => false
> b.a
  => (db request for "a")
> b.ivar('a')
  => (returns "a" object, as when b.a is called)

Upvotes: 0

Upendra Chahar
Upendra Chahar

Reputation: 116

It's a enumerable method of this Class: Mongoid::Relations::Targets::Enumerable

_loaded?

it will return true and false if Has the enumerable been _loaded? This will be true if the criteria has been executed or we manually load the entire thing.

Upvotes: 1

Related Questions