Carsten Gehling wrote: > My head is spinning a bit this morning - can somebody help me with this? > > Given these two models with the following associations: > > class Article < ActiveRecord::Base > belongs_to :category > > - has an attribute called "published_on" > end > > class Category < ActiveRecord::Base > has_many :articles > end > > > I need to list all categories, the order should be determined by the > "published_on" date of their latest associated article. > > So for example: > > cat1 = Category.create > cat1.articles.create(:published_on => 5.days.ago) > cat1.articles.create(:published_on => 4.days.ago) > > cat2 = Category.create > cat2.articles.create(:published_on => 2.days.ago) > > Then my list should be ordered: > > [cat2, cat1] > > I believe this would be trivial to make in raw SQL, but I have trouble > figuring out, how to do it with AR's find() method. > > - Carsten
Hey Carsten Are you aware that you can include associations in find queries with ":include" http://api.rubyonrails.org/classes/ActiveRecord/Base.html Off the top of my head, try: Category.all :include => :articles, :order => "articles.published_on DESC" Let me know if that works Cheers, Gavin http://handyrailstips.com -- Posted via http://www.ruby-forum.com/. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---

