4 ms·
Much like other ORMs, ActiveRecord makes it almost effortless to accidentally do very stupid queries in bulk. For example (from http://guides.rubyonrails.org/ac
by prodigal_erik 16y ago
Much like other ORMs, ActiveRecord makes it almost effortless to accidentally do very stupid queries in bulk. For example (from http://guides.rubyonrails.org/active_record_querying.html http://guides.rubyonrails.org/active_record_querying.html) this code
clients = Client.all(:limit => 10)
clients.each do |client|
puts client.address.postcode
end
looks harmless but requires eleven sequential round-trips to the database. This version
clients = Client.includes(:address).limit(10)
clients.each do |client|
puts client.address.postcode
end
still requires two, and one of the queries gets bigger as the number of ids increases. You can get into find_by_sql, but at that point ActiveRecord isn't adding any value.
- rbranson 16y agoSure, but how many times have you seen someone create something equal to that with SQL queries? Instead of using a join, they execute a SELECT against the database for every row they fetch. This is shockingly common in horribly written PHP code. In addition, ActiveRecord also supports joins instead of using includes. Includes is almost always fine, unless the initial result set is large (100+ rows).
- chrisbolt 16y agoAt least with SQL, it's obvious and not hidden by a layer of abstraction.