Rails association data: preload, eager_load, includes, join
mouse 293 · person cloud · link
Last update
2017-07-27
2017
07-27
«recap on the four methods available on rails to query/load association data»

preload

Loads data in a separate query (we cannot place conditions on the association):

1
User.preload(:posts)
1
2
SELECT users.* FROM users
SELECT posts.* FROM posts WHERE posts.user_id IN (1)


eager_load

Loads data in a single LEFT OUTER JOIN query (we can place conditions on the association):

1
User.eager_load(:posts)
1
2
3
SELECT users.id AS t0_r0, users.name AS t0_r1   , users....,
       posts.id AS t1_r0, posts.user_id AS t1_r1, posts....
FROM users LEFT OUTER JOIN posts ON posts.user_id = users.id


includes

Loads data in a separate or single query based on conditions:

1
2
User.includes(:posts)
User.includes(:posts).where(posts: {title: 'hello'})
1
2
3
4
5
6
7
8
9
-- 1st case - without conditions
SELECT users.* FROM users
SELECT posts.* FROM posts WHERE posts.user_id IN (1)

-- 2nd case - with conditions
SELECT users.id AS t0_r0, users.name AS t0_r1   , users....,
       posts.id AS t1_r0, posts.user_id AS t1_r1, posts....
FROM users LEFT OUTER JOIN posts ON posts.user_id = users.id
WHERE posts.title = 'hello'


join

Does not load any data, just uses an INNER JOIN query:

1
User.joins(:posts)
1
SELECT users.* FROM users INNER JOIN posts ON posts.user_id = users.id

Source: BigBinary