Home Rails includes vs all?
Reply: 0

Rails includes vs all?

user2381
1#
user2381 Published in April 22, 2018, 5:02 am

I am going back to refresh my Rails knowledge by watching some tutorials, and I came across where the tutorial rails app uses includes() on index.

  def index
    @books = Book.all
  end

vs

  def index
    @books = Book.includes(:author, :genre)
  end

As a side note, book belongs_to author and genre. Author has_many books and genre also has_many books.

When all is used, it looks like this when I refresh page:

 Rendering books/index.html.erb within layouts/application
  Book Load (1.4ms)  SELECT "books".* FROM "books"
  Author Load (0.3ms)  SELECT  "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  Genre Load (0.3ms)  SELECT  "genres".* FROM "genres" WHERE "genres"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  Author Load (0.4ms)  SELECT  "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Genre Load (0.3ms)  SELECT  "genres".* FROM "genres" WHERE "genres"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "genres".* FROM "genres" WHERE "genres"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "authors".* FROM "authors" WHERE "authors"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  CACHE (0.0ms)  SELECT  "genres".* FROM "genres" WHERE "genres"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]

When includes is used, when I reload the page it shows:

  Rendering books/index.html.erb within layouts/application
  Book Load (0.4ms)  SELECT "books".* FROM "books"
  Author Load (0.5ms)  SELECT "authors".* FROM "authors" WHERE "authors"."id" IN (2, 1)
  Genre Load (0.4ms)  SELECT "genres".* FROM "genres" WHERE "genres"."id" IN (2, 3)

I think this makes includes far more efficient than all because it hits the entire model database.

My question is, why do people still use all? Why not completely eradicate all and use includes from now on? Is there any situation where I would prefer to use all and not use includes? I am using Rails 5.0.1.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303953 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO