Rails association data: preload, eager_load, includes, join
Last update
2024-06-18
2024-06-18
«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 2 | User.joins(:posts) User.joins("LEFT OUTER JOIN comments ON comments.user_id = users.id") |
1 2 | SELECT users.* FROM users INNER JOIN posts ON posts.user_id = users.id SELECT users.* FROM users LEFT OUTER JOIN comments ON comments.user_id = users.id |
Source: BigBinary