Ruby on Rails: Model.all.each vs find_by_sql ("SELECT * FROM model").

I am new to RoR. In my controller, I repeat all the tuples in the database. For each table for each column that I used to call

SomeOtherModel.find_by_sql("SELECT column FROM model").each {|x| #etc }

which worked well enough. When I later changed it to

Model.all(:select => "column").each {|x| #etc }

the cycle starts at about the same speed, but it slows down quickly to about 100 times slower than the find_by_sql command. These calls must be identical, so I really don't know what is going on.

I know that these challenges are not the most effective, but this is just an intermediate step, and I will optimize it more as soon as it works correctly.

So to clarify: why is the call to Model.all.each in the world much slower than using find_by_sql.each?

Thank!

+3
source share
2 answers

SQL, . Model.all . , Rails all , , . find_by_sql 1 . , . ? 100 , , find_in_batches. . select, . :

Model.find_in_batches(:batch_size => 100) do |group|
  group.each {|item| item.do_something_interesting }
end
+7
, . find_by_sql , B_. , Model.all . . FYI, Rails Guides: http://guides.rubyonrails.org/active_record_querying.html#retrieving-multiple-objects
+2

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


All Articles