Why to use relation? Why not use relation?
rails g scaffold book title
First layer: table
In migration file
rake db:create db:migrate
Second layer: model
In model directory
cp book.rb page.rb
Note: No 's' here, we don't want to generate a method with 's'
Third layer: view
Now its N+1
Generate 20 books each of them has 10 pages
Load page '/books' and see the log
Here we encounter N+1 query
Because pages are under books, to load pages, we have to do a lot of query
The query algorithm is very quickly, mysql is slow because:
- 80% of time are used to parse the mysql comment.
- 2 times latency
So it's important to reduce query times as less as possible.
To solve this, we use ruby way, not rails way
- Pick up all ids
In books controller
Now the query becomes