includes vs. joins in Rails

includes

Eager load the included associations into memory. Fire two queries:

1
2
SELECT "products".* FROM "products" ORDER BY name
SELECT "categories".* FROM "categories" WHERE "categories"."id" IN (2, 1, 5, 4, 3)

joins

Sometimes,includes will load many redundant fields in association table, joins help to control what columns after SELECT.

Reference


Does query with includes and joins return the same count?

activerecord-includes-joins-query-countlink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

class BugTest < Minitest::Test
  def test_association_stuff
    post1 = Post.create!
    post2 = Post.create!

    post1.comments << Comment.create!
    post1.comments << Comment.create!
    post2.comments << Comment.create!
    post2.comments << Comment.create!
    post2.comments << Comment.create!

    assert_equal 2, Post.includes(:comments).find(post1.id, post2.id).count
    # => SELECT "posts".* FROM "posts" WHERE "posts"."id" IN (1, 2)
    # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" IN (1, 2)

    assert_equal 5, Post.joins(:comments).where(id: [post1.id, post2.id]).count
    # => SELECT COUNT(*) FROM "posts" INNER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE "posts"."id" IN (1, 2)

  end
end

Does includes work with Mongoid?

Check list:

By now ( 2014-05-08 ) the latest version 4.0.0.beta1 behaves much better than last stable version 3.1.6, check the gist.

rails-includes_vs_joins