When creating web applications, always a need arises when we have to iterate over a large number of records.
This process is called retrieving multiple objects in batches. This can be done through find_each method.
The find_each method by default iterates over 1000 records and then yield each record individually to the block as a model.
Now suppose we have an Employee table and those employees have subscribed for magazines.
So now we will have to iterate through all the employees to send them magazines. We can do it as follows :
Employee.find_each do |employee|
MagazineMailer.weekly(employee).deliver_now
end
or we can write
Employee.where(weekly_subscription: "true").find_each do |employee|
MagazineMailer.weekly(employee).deliver_now
end
The find_each method has some options namely :
The batch_size method allows us to tell the find each method on how many records to iterate over.
Lets say if we want the find_each method to iterate over first 3000 employees then we can do it like this.
Employee.find_each(batch_size: 3000) do |employee|
MagazineMailer.weekly(employee).deliver_now
end
The start method allows us to tell the find each method from where to start the iterating over the records.
Lets say if we want the find_each method to start iterating from the record with primary key 500 then it would be done like this.
Employee.find_each(start: 500, batch_size: 3000) do |employee|
MagazineMailer.weekly(employee).deliver_now
end
The finish method allows us to tell the find each method where to end the iterating over the records.
Lets say if we want the find_each method to start iterating from the record with primary key 500 and finish the iteration on primary key 2000 then it would be done like this.
Employee.find_each(start: 500, finish: 2000) do |employee|
MagazineMailer.weekly(employee).deliver_now
end
So hope this blog was helpful to understand the find_each method and its options.
0 Comment(s)