Calling @books.photos.find(blah) vs getting record set first

Which one is better?

@book.photos.count(:conditions=>[“uploader_id=?”,@c.id])
@book.photos.find(:all,:conditions=>[“uploader_id=?”,@c.id],:offset=>@offset,:limit=>@limit)

OR

book = @book.photos
book.count(:conditions=>[“uploader_id=?”,@c.id])
book.find(:all,:conditions=>[“uploader_id=?”,@c.id],:offset=>@offset,:limit=>@limit)

I heard that when you do @book.photo.find(blah), it actually does ONE
query by combining them, same thing going for the count which I believe
use count(*).

So I think the first one is better… any thoughts?

On Dec 21, 6:54 pm, Aryk G. [email protected]
wrote:

Which one is better?

@book.photos.count(:conditions=>[“uploader_id=?”,@c.id])
@book.photos.find(:all,:conditions=>[“uploader_id=?”,@c.id],:offset=>@offset,:limit=>@limit)

OR

book = @book.photos
book.count(:conditions=>[“uploader_id=?”,@c.id])
book.find(:all,:conditions=>[“uploader_id=?”,@c.id],:offset=>@offset,:limit=>@limit)

Is this a trick question? :wink: They are exactly the same

book = @book.photos
book.object_id == @book.photos.object_id => true

Aaron

Aaron, somewhere I heard that when you do @book.photos.find(blah), it
actually does @book.find(:all,:conditions=>“photo_id=blah”).find(blah)
and then COMBINES the two queries into one, effectively doing just one
query.

However if i do [email protected] I do a query. Then if I do
book.find(blah) and then Im doing two queries.

Where am I going wrong with this?

Hey Mark, thanks for the response…

Of course, this depends on whether @site has already had it’s ‘pages’
attribute loaded. For each instance of the Site class, once the ‘pages’
attribute has been loaded from the database it will stay in memory and
so subsequent calls to ‘@site.pages’ will not result in a db hit.

When you say already had its pages loaded, are you saying that somewhere
earlier in the action, @site.pages was called, so it was already cached
for that method. I didnt know RoR could do that.

Aryk,

The first one is quicker, as it only performs one query.

@site.pages.count’ results in this query:

SELECT count(*) AS count_all FROM pages WHERE (pages.site_id = X)

The second one performs two queries, and the first may return lots of
records which you do not need.

‘pages = @sites.pages; pages.count’ result in two queries:

SELECT * FROM pages WHERE (pages.site_id = X)
SELECT count(*) AS count_all FROM pages WHERE (pages.site_id = X)

Of course, this depends on whether @site has already had it’s ‘pages’
attribute loaded. For each instance of the Site class, once the ‘pages’
attribute has been loaded from the database it will stay in memory and
so subsequent calls to ‘@site.pages’ will not result in a db hit.

Cheers,

Mark

PS. X = @site.id