Include only the latest/newest associated record with active record?

Posted by railsnewbie on Stack Overflow See other posts from Stack Overflow or by railsnewbie
Published on 2014-05-29T18:06:49Z Indexed on 2014/05/30 9:27 UTC
Read the original article Hit count: 116

is it possible to load only the latest associated record of an associated table?

an example:

class author
  attr_accessible :first_name, :last_name, :birthday
  has_many :books
end

class book
  attr_accessible :pages, :date of publication, :title
  belongs_to :author
end

Is there a way to generate a scope to load only the newest released book the author wrote? Or the book with the most pages?

I know, that I could include or join all books. But I don't know if its possible to load only a specific book for each author.

So that I could do a query like this:

Author.authors_and_their_newest_book

So that I could get these results

first_name_author_1, last_name_author_1, birthday_author_1, pages_book_3, date of publication_book_3, title_book_3
first_name_author_2, last_name_author_2, birthday_author_2, pages_book_5, date of publication_book_5, title_book_5
first_name_author_3, last_name_author_3, birthday_author_3, pages_book_9, date of 

publication_book_9, title_book_9 ...

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about activerecord