Это добавляет немного накладных расходов, но экономит сложность и увеличивает скорость позже, когда это имеет значение.
Добавить столбец «Most_recent» в книги.Убедитесь, что вы добавили индекс.
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
Затем, когда вы сохраняете книгу, обновите 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
Теперь, для вашего запроса
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позволяет вам написать это так, и в результате получается отношение, которое будет использоваться с другими областями.
User.last_book_completed