Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Optimize named_scope first and last to use LIMIT rather than loading the full collection

#749

I wanted to use Account.recent.first(5) to display the most recent 5 accounts in the system. I noticed that this was loading the whole table into memory rather than using a LIMIT 5.

When I dug in I noticed that Account.first(5) returned only the first record.

Goal: make this two calls efficient and consistent with first and last on Array.

Reported by Lars Klevan · August 2nd, 2008 @ 07:02 PM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: Low

Activity

  1. José Valim
    José Valim
    • Tag changed from activerecord, performance to activerecord, patch, performance

    It sounds great for me!

    +1

    August 3rd, 2008 @ 11:18 AM

  2. DHH
    DHH
    • State changed from new to incomplete

    Looks really nice. Needs doc updates, though.

    September 10th, 2008 @ 06:32 AM

  3. Lars Klevan
    Lars Klevan

    Updated the docs for ActiveRecord#first and #last. Example for #first below.

    A convenience wrapper for find(:first, *args). You can pass in all the

    same arguments to this method as you can to find(:first) If the first

    argument is an integer an array of the first n records will be returned.

    #

    ==== Examples

    #

    Person.first # Equivalent to Person.find(:first)

    Person.first(:conditions => [ "user_name = ?", user_name])

    Person.first(5) # Equivalent to Person.find(:all, :limit => 5)

    Person.first(5, :conditions => [ "user_name = ?", user_name])

    September 15th, 2008 @ 11:24 PM

  4. Daniel Schierbeck
    Daniel Schierbeck

    +1, simple and concise implementation.

    October 20th, 2008 @ 11:15 PM

  5. Pratik
    Pratik
    • State changed from incomplete to resolved

    No longer needed.

    January 21st, 2010 @ 04:14 PM

  6. Jeff Kreeftmeijer
    Jeff Kreeftmeijer
    • Tag cleared.
    • Importance changed from to Low

    Automatic cleanup of spam.

    October 12th, 2010 @ 09:06 AM

  7. Aditya Sanghi
    Aditya Sanghi

    Automatic cleanup of spam.

    October 12th, 2010 @ 10:16 AM