Why did my Rails find query select all records?
I have skipped the code along these lines:
MyUserModel.find([id1, id2, id3]) do |record| send_email(record) end
As you can see, I forgot to include .each
after find
. Apparently this led to what send_email
gets called on every record in the table my_user_model
. I don't understand why this happened. Can someone please explain?
I'm new to ruby ββand rails, so I guess I just don't understand how blocks or something works.
source to share
Passing a block to find
changes the behavior of the method. As a result, all loads will be loaded and then only those for which the supplied block returns are returned true
, as opposed to how it works Enumerable#find
.
If you did something like:
MyUserModel.find { |m| [1,2,3].include?(m.id) }
Then you will have an equivalent version, although this is slower since all records have to be loaded and not filtered at the database level.
Typically, you want to write it as:
MyUserModel.where(id: [ 1, 2, 3 ]).each do |model|
# ...
end
source to share