This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total.
This code looks fine at first sight. But the problem lies within the total number of queries executed. The above code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = **11** queries in total.
**Solution to N + 1 queries problem**
...
...
@@ -1453,7 +1453,7 @@ User.active.inactive
# SELECT "users".* FROM "users" WHERE "users"."state" = 'active' AND "users"."state" = 'inactive'
```
We can mix and match `scope` and `where` conditions and the final sql
We can mix and match `scope` and `where` conditions and the final SQL
will have all conditions joined with `AND`.
```ruby
...
...
@@ -1750,7 +1750,7 @@ Client.connection.select_all("SELECT first_name, created_at FROM clients WHERE i
### `pluck`
`pluck` can be used to query single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
`pluck` can be used to query single or multiple columns from the underlying table of a model. It accepts a list of column names as an argument and returns an array of values of the specified columns with the corresponding data type.
@@ -171,7 +171,7 @@ Similarly, in the Rails console, if you have a user instance and reload:
> reload!
```
the `user` object is instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is instance of.
the `user` object is an instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is an instance of.
Another use case of this gotcha is subclassing reloadable classes in a place that is not reloaded: