Eager_Loading

33 views
Skip to first unread message

Joe

unread,
Mar 14, 2011, 5:44:12 PM3/14/11
to Paperclip Plugin
I'm trying to eager load so that I don't have to make so many database
queries...

Basically, I have

Parent > Child > Data

Parent has_many => :child
Child has_attached_file => :data

Since :data isn't a real model, I cannot seem to eager load it.

I'm trying to get the URLs for the :data that is attached to the
parent through the child. So that I can link to them in a list of the
parent. The problem is that I have been unable to do anything to to
eager load these, so I have 2 queries for each parent in order to
obtain the 2 urls that I need.

I could simply create the URLs myself, since they're all fairly static
based on the id of the parent and child models. But I was wondering if
Paperclip already has a way to deal with this.

Jon Yurek

unread,
Mar 21, 2011, 10:35:08 AM3/21/11
to papercli...@googlegroups.com
Hi,

I'm not sure what you mean by "eager loading" of Data, here. If you eager load all the Children through the Parents, you have everything you need to get the URL of the Data attachment. URLs are calculated, not stored. The data stored for the Data attachment is stored on the Child model, and it's only the file name, size, content type, and updated_at. You don't need to make any queries to get the URL for the attachment. You will need to make more method calls, but that doesn't incur the same cost.

For example, this should only require two hit to the database, total:

parent = Parent.all(:include => :child)
parent.children.map do |child|
child.data.url
end

It would be one for all the Parents and one for all the associated Children, since that's how AR does eager loading.

Is that not what you're seeing?

> --
> Individuals over processes. Interactions over tools.
>
> Agile Rails training from thoughtbot, the makers of Paperclip, Clearance, Shoulda, & Factory Girl:
> http://thoughtbot.com/services/training
>
> The Paperclip group:
> http://groups.google.com/group/paperclip-plugin
>
> To post to this group, send email to
> papercli...@googlegroups.com
>
> To unsubscribe from this group, send email to
> paperclip-plug...@googlegroups.com


--
Jonathan Yurek, Founder and CTO
thoughtbot, inc.
617.482.1300 x114
http://thoughtbot.com/
http://twitter.com/thoughtbot

Reply all
Reply to author
Forward
0 new messages