Active record tips




1 map vs pluck

Client.all.map(&:email) => SELECT "clients".* FROM "clients" => 0.0306 s

Client.pluck(:email) => SELECT "clients"."email" FROM "clients" => 0.0040 s

2 pluck

Client.pluck(:id) == Client.ids

3 sum

Order.sum(:total) => SELECT SUM("orders"."total") FROM "orders" => 0.0032 s
Order.sum(&:total) => SELECT "orders".* FROM "orders" => 0.0916 s

 4. uniq

Order.pluck(:email).uniq => SELECT "orders"."email" FROM "orders" => 0.0762 s
Order.uniq.pluck(:email) => SELECT DISTINCT "orders"."email" FROM "orders" => 0.0197 s

5 update_all

Order.where(state: 'cart').where('updated_at < ?', 7.days.ago).each do |order|
  order.update(inactive: true)
end => Count of orders requests 

Order.where(state: 'cart').where('updated_at < ?', 7.days.ago).update_all(inactive: true)
Ruby
One request.

(c) https://www.netguru.co/

Comments