I have a Model in my Rails app named User
, which has an attribute name
Let's say I want to find all Users
whose name
matches a specific string.
In a Rails Console, I could do:
OPTION 1
User.where("name LIKE 'string'")
This is very fast.
OPTION 2
User.select{|u| u.name == "string"}
This is extremely slow. It works for a small database, but if you have hundreds of thousands of users, this appears to try to load all Users
into memory first, and then iterate them in the block.
Does this mean that option 2 is always wrong ? What's the correct use case for .select
then, when is it preferable over .where
?
I wrote a bunch of code in my app that is working fine using .select
, but now that I tried using over a very large table I saw that I might be doing something wrong.
Aucun commentaire:
Enregistrer un commentaire