How to find the most recent associations created between two objects with Rails?

Posted by Kevin on Stack Overflow See other posts from Stack Overflow or by Kevin
Published on 2010-03-16T16:30:46Z Indexed on 2010/03/16 17:11 UTC
Read the original article Hit count: 212

Filed under:

Hi,

I have a user model, a movie model and this association in user.rb (I use has_many :through because there are other associations between these two models):

has_many :has_seens
has_many :movies_seen, :through => :has_seens, :source => :movie

I'm trying to get an array of the ten most recent has_seens associations created.

For now, the only solution I found is to crawl through all the users, creating an array with every user.has_seens found, then sort the array by has_seen.created_at and only keep the last 10 items… Seems like a heavy operation.

Is there a better way?

Kevin

© Stack Overflow or respective owner

Related posts about ruby-on-rails