Jesse Aldridge
Jesse Aldridge

Reputation: 8149

Why did my Rails find query select all records?

I ran some 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 the find. This seems to have resulted in send_email being called on every record in the my_user_model table. I don't understand why this happened. Can someone explain?

I'm new to ruby and rails, so I assume I'm just not understanding something about how blocks work or something like that.

Upvotes: 3

Views: 72

Answers (1)

tadman
tadman

Reputation: 211600

Passing a block to find changes the behaviour of the method. What ends up happening is it will load all models, then return only those for which the supplied block returns true, not unlike how Enumerable#find works.

If you did something like:

MyUserModel.find { |m| [1,2,3].include?(m.id) }

Then you'd have an equivalent version, though this one is way slower since all records must be loaded rather than filtering at the database level.

Generally you'd want to write this as:

MyUserModel.where(id: [ 1, 2, 3 ]).each do |model|
  # ...
end

Upvotes: 4

Related Questions