Question

Need that the active record should be in group or batch of two record.

Because i needs to loop the active record in group of twos.

currently i am getting all the data in format like for example

[#<users id: 2, title: "mr">,
 #<users id: 3, title: "mr">,
 #<users id: 4, title: "mr">,
 #<users id: 5, title: "mr">]

I the data like this,

[
    [#<users id: 2, title: "mr">, #<users id: 3, title: "mr">],
    [#<users id: 4, title: "mr">, #<users id: 5, title: "mr">]
]

This can be done by looping and push the data and create arrays manually, but I need it to be done by ActiveRecord.

Was it helpful?

Solution

So ActiveRecord has a find_in_batches method that will let you process table results in small groups instead of retrieving all the records from the database at once, but it sounds like you just want to avoid having to write loops to group your records into the array format that you want.

If that is the case, you can actually do that easily using the Enumerable#each_slice method:

User.all.each_slice(2).to_a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top