This project is archived and is in readonly mode.
eager loading of associations not working in rails 3?
-
Jason May
- No changes were found…
-
Jason May
- Tag changed from arel activerecord bug rails3, eager, eager_loading to activerecord 3.0, rails 3, activerecord, arel, eager, eager_loading
-
Emilio Tagua
Hey Jason,
Can you provide a failing test or something more specific, because i tried this on master:
Post.joins(:comments).includes(:comments).all
and you get this 2 queries:
SELECT "posts". FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id"
SELECT "comments". FROM "comments" WHERE ("comments".post_id IN (1,2,4,5,7)).Which shows eager loading is working properly.
-
Jason May
I see...
I had thought that
includes(:bar)would generate anOUTER JOINclause in the original SQL, rather than generating a secondSELECTwith anINclause, i.e.Post.includes(:comments).allwould generate (for
has_many)SELECT "posts".*, "comments".* FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"instead of
SELECT "posts".* FROM "posts" SELECT "comments". FROM "comments" WHERE ("comments".post_id IN (...))My problem is that the 2-query situation doesn't allow for iterating through the results without pre-fetching everything. Doesn't that bust Arel's closure objective?
-
José Valim
- Assigned user set to Emilio Tagua
- Milestone cleared.
-
Emilio Tagua
- State changed from new to invalid
Hey Jason,
This 2 queries is the expected behavior, you would get one query with an OUTER JOIN if any restriction includes a reference in conditions, order, etc. in the other table (check out references_eager_loaded_tables? in ActiveRecord::Relation).
Fox exmaple:
Post.find(:first, :include => :comments, :conditions => "posts.title = 'Welcome to the weblog'")
When this doesn't happen preload is used which executes this 2 queries, which do pre-fetch everything in a better way, that 2 queries are better than having just 1 with a join by default.
I'm marking this ticket as invalid as it doesn't look like a bug but feel free to continue discussing if i'm not making things clear for you.
-
Jason May
Hi Emilio-
I think your example should have
comments.titlein the conditions instead ofpost.title.Is it possible to express your example using Arel-style syntax? Something like
Post.includes(:comment).where(comment[:title].eq("Welcome..."))I'm not sure how to refer to
commenthere, the example code I could find refers to anArel::Tablemethod but this seems to be private.Thanks,
-Jason -
Emilio Tagua
Jason,
You could try something like this:
Post.includes(:comments).where(Comment.arel_table[:title].eq("Welcome ...")) -
Ryan Bigg
Automatic cleanup of spam.
-
Ryan Bigg
Automatic cleanup of spam.
-
Jeff Kreeftmeijer
Automatic cleanup of spam.