I have 2 following models:
class Schedule < ActiveRecord::Base
attr_accessible :description, :deadline_on, :repeat
has_many :scheduled_transactions
end
class ScheduledTransaction < ActiveRecord::Base
attr_accessible :transaction_on, :description
belongs_to :schedule
end
I want to find last scheduled transactions from each schedule. I know I can do:
Schedule.all.each do |schedule|
schedule.scheduled_transactions.order(:transaction_on).last
end
but I want to optimize it and make a single database select.
I tried to construct Rails query:
ScheduledTransaction.select('DISTINCT(schedule_id), scheduled_transactions.*').order('transaction_on DESC')
which was translated into:
SELECT DISTINCT(schedule_id), scheduled_transactions.* FROM "scheduled_transactions" ORDER BY transaction_on DESC
but it doesn't give expected results. There are multiple rows with same schedule_id.
And my goal is to select list of scheduled transactions containing last scheduled transaction for each schedule. Any suggestions?
(PostgreSQL) 9.1.9