0

I have the following scope in my Order model:

scope :trial_almost_up, lambda { where :date_finished => 27.days.ago.midnight..27.days.ago.end_of_day }

Each order is tied to a User. So if you run Order.trial_almost_up and get an array of orders and run this:

o = Order.trial_almost_up
o.collect &:user

The collect runs a separate SQL statement for each Order that is tied to the user.

User Load (0.6ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 11244 LIMIT 1
  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1970 LIMIT 1

Is there anyway to combine this into one call?

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

1

You can do this. I don't know if there is a better way but this one is the only one that I can think of right now.

User.includes(:orders).where("orders.date_finished" => 27.days.ago.midnight..27.days.ago.end_of_day)

Let me know if it works, I'll edit this if I find something better

rogeliog
  • 3,632
  • 4
  • 27
  • 26