This adds a little overhead, but saves complexity and increases speed later when it matters.
Add a "most_recent" column to books. Make sure you add an index.
class AddMostRecentToBooks < ActiveRecord::Migration
def self.change
add_column :books, :most_recent, :boolean, :default => false, :null => false
end
add_index :books, :most_recent, where: :most_recent # partial index
end
Then, when you save a book, update most_recent
class Book < ActiveRecord::Base
on_save :mark_most_recent
def mark_most_recent
user.books.order(:created_at => :desc).offset(1).update_all(:most_recent => false)
user.books.order(:created_at => :desc).limit(1).update_all(:most_recent => true)
end
end
Now, for your query
class User < ActiveRecord::Base
# Could also include and preload most-recent book this way for lists if you wanted
has_one :most_recent_book, -> { where(:most_recent => true) }, :class_name => 'Book'
scope :last_book_completed, -> { joins(:books).where(:books => { :most_recent => true, :complete => true })
end
This allows you to write it like this and the result is a Relation to be used with other scopes.
User.last_book_completed