Eager Loading Dependencies (such as images)


(Griffin) #1

Is there a way to load all images associated to a given node in a single query such as using active record’s includes method?

Currently on my homepage I am loading several types of nodes, all of which have several images and I am generating an excessive amount of queries.

Thanks in advance for any help.


(Aaron Russell) #2

Hi @gmahoney. Good question, although not sure I’ve got a good answer.

It is possible to lazily load child nodes, eg:

PushType::Node.includes(:children)

But I’m afriad for nodes with field types that are related to other database objects this isn’t easily possible. Relation fields don’t behave like real relations like you’d expect using has_many and belongs_to methods.

If we dug deep enough I suspect it would be possible to add this kind of behaviour - and I totally see the value in doing so - but right now my knowlegde of the internals of active record isn’t quite string enough to attempt this. Would be a valuable PR if anyone fancies diving in?

So as it stands now, if you’re concerned about the number of queries on a specific page, I think your best bet is to implement caching in the view.


(Griffin) #3

Thanks Aaron, I will consider this PR in the coming months.