I have a structure something like this:
class User
has_many :dongles
has_many :licences, :through => :dongles
end
class Dongle
has_many :licences
belongs_to :user
end
class Licence
belongs_to :dongle
end
However, time passes and the user eventually gets multiple licences for each dongle. Reasonably, the app wants to summarise the most recent licences for each.
I know I can naively do it like this:
user.dongles.each do |dongle|
licence = dongle.licences.find(:first, :order => 'created_at DESC')
# do something with the licence info
end
But is there a way to do this through the collection and avoid the large number of queries which would normally result by doing it the naive way?
I tried this:
user.licences.find(:all, :order => 'created_at DESC', :group => 'dongle_id')
This does return one licence for each dongle, but the first one it takes is decided by 'id', not by the order I have specified in the query.
Is there a way I can get it to give me the first of each, using a sort order I provide to decide which is the first?