How to use order in find_each rails

I really don't know if anyone asked this question or not, if someone has already asked about it, please let me know.

I want to use order with find_each. It should be something like

Email.find_each(:order=> "id desc").do |email|
  puts "email.id"
end

Thanks in advance

+4
source share
3 answers

Since it find_eachuses internally find_in_batches, which forces the order to grow on the primary key ( id ASCby default) and does not allow changing it, this is impossible.

More details here:

http://api.rubyonrails.org/classes/ActiveRecord/Batches.html

+18
source

, , , , , - . find_each, , ActiveRecord .

create a file active_record.rb in config/initializers

if primary_key_offset
  records= relation.where(table[primary_key].lt(primary_key_offset)).to_a
end
def batch_size
  "#{quoted_table_name}.#{quoted_primary_key} DESC"
end
0
Email.all.sort {|a, b| b[:id] <=> a[:id]}.each do |email|
  puts "email.id"
end
-7
source

Source: https://habr.com/ru/post/1529788/


All Articles