remi
remi

Reputation: 1303

Differentiate two ActiveRecord association instances, one that was eager loaded and one that was not

Let’s say I have these ActiveRecord models:

class User < ActiveRecord::Base
  has_many :emotions
end

class Emotion < ActiveRecord::Base
  belongs_to :user
end

And I have this code:

user1 = User.where(id: 1).includes(:emotions).first
user2 = User.where(id: 1).first

Is there a way to differentiate user1.emotions and user2.emotions? Is there a method I can call on them to know if the relation has been eager loaded or is still waiting to be queried from the database?

Upvotes: 1

Views: 62

Answers (1)

remi
remi

Reputation: 1303

I should have just looked into ActiveRecord’s source code.

user1.emotions.loaded? # => true
user2.emotions.loaded? # => false

#loaded? is what I was looking for.

Upvotes: 2

Related Questions