This project is archived and is in readonly mode.

#3594 ✓resolved
Emilio Tagua

ActiveRecord::Relation#to_a should be cachable

Reported by Emilio Tagua | December 17th, 2009 @ 06:13 PM


Right now there's performance issue in ActiveRecord::Relation#to_a:

@posts = Post.all { ... }

Returns a relation. Ok, then if we do something like: { ... }

Relation#to_a gets called and the records are initialized and loaded, this is ok, but if we do:

@posts.each { ... }

The records will be initialized all over again. This patch fixes this by adding memoization to Relation#to_a and unmemoizing when Base#all gets called.

@posts = Post.all { ... } # All records

@posts = Post.all :limit => 1 { ... } # Only the first record

Comments and changes to this ticket

  • David Trasbo

    David Trasbo June 13th, 2010 @ 08:02 PM

    • Assigned user set to “Ryan Bigg”

    This has been solved - not by using memoization though:

    def to_a
      return @records if loaded?
      @records = eager_loading? ? find_with_associations : @klass.find_by_sql(arel.to_sql)
      # ...
      @loaded = true
    def loaded?

    This ticket can be closed.

  • Emilio Tagua

    Emilio Tagua June 13th, 2010 @ 11:03 PM

    • State changed from “new” to “resolved”
    • Assigned user changed from “Ryan Bigg” to “Emilio Tagua”

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href=""></a>