You should be able to accomplish this by adding an :order
clause to the has_many :has_seens
association to order them by the creation date. Then use an association extension to define a method on the association itself:
class User < ActiveRecord::Base
has_many :has_seens, :order => 'created_at DESC' do
def recent(count=10)
all(:limit => count)
end
end
end
Now you can use user.has_seens.recent
to get the most recent ten movies seen. Optionally, pass in a different count e.g. user.has_seens.recent(25)
.
Incidentally, I think that viewings
is a less awkward association name than has_seens
!
Edit: Personally, I would arrange things with a Viewing
join model, like this:
class User < ActiveRecord::Base
has_many :viewings
has_many :movies, :through => :viewings
end
class Viewing < ActiveRecord::Base
belongs_to :user
belongs_to :movie
default_scope :order => 'created_at DESC'
# Recent n viewings for any user
named_scope :recent, lambda { |count| { :limit => count }}
end
class Movie < ActiveRecord::Base
has_many :viewings
has_many :users, :through => :viewings
end
I've used a default scope on the Viewing
model, but you could specify the ordering on the associations if viewings should be ordered by some other attribute other than creation date by default.
Now you can do:
# 10 most recent viewings for everyone
recent = Viewing.recent(10)