are association extensions efficient?

Hi --

hi guys, Ive noticed that you can add association extensions to
activerecord associations. Wouldnt it just be better to make a complete
new sql or activerecord query instead of doing something like:

@c.received_messages.find(new conditions)

Isnt this like doing TWO database queries, wouldn't it just be better to
combine it from the start?

Have you looked at your log file? :slight_smile: You might be pleasantly
surprised.

The AR collection that you get back from @c.received_messages is
actually a kind of collection proxy. It queries the database lazily;
in other words, it waits for evidence that you really need the items
in the collection before it goes and gets them.

That means it can avoid hitting the database until *after* it gets
your 'find' message. The result is that it can combine everything
into one database query.

Here's a little demo, from a console session for a demo program I've
got lying around:

t = Tag.find(1)

=> #<Tag:0xb76de20c @attributes={"body"=>"Device", "id"=>"1"}>

t.things.find(:first)

=> #<Thing:0xb76c7098 @readonly=true, @attributes={"thing_id"=>"1",
"tag_id"=>"1", "id"=>"21"}>

And here's the SQL:

   SELECT * FROM things INNER JOIN tags_things ON things.id =
   tags_things.thing_id WHERE (tags_things.tag_id = 1 ) LIMIT 1

Note that it didn't get all the things first; it just did one query.

I'm not sure whether there are cases, perhaps involving complex
associations with custom SQL, where this optimization isn't done, but
in the general case it is.

David