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.

Query cache broken when using associations with scopes

#4708

I assume that the following should fire one sql query for each line:

u = User.first
u.posts.older_than 2.seconds
u.posts.older_than 2.hours

For me, it doesn't. The third line does not fire an sql query. Instead, it returns whatever line two returned.

Here's how to repeat this:

1) Create a new Rails app
2) script/rails g model User
3) script/rails g model Post user:references
4) Define this association in user.rb: has_many :posts
5) Define this scope in post.rb: scope :older_than, lambda {|period| where 'created_at < ?', period.ago }
6) Go to the console
7) Run the code written at the top of this ticket while tailing the log file. Only two queries are fired.

I'm using Rails3 beta3 and Ruby 1.9.1 on Mac OSX.

Reported by Rasmus Rønn Nielsen · May 26th, 2010 @ 04:51 PM

State: resolved
Milestone: none
Assigned to: Pratik Pratik
Importance: Low

Activity

  1. Neeraj Singh
    Neeraj Singh
    • Tag changed from 3.0 to 3.0, activerecord

    Attached is a failing test. I am using ruby 1.8.7 and am able to reproduce it.

    May 26th, 2010 @ 09:22 PM

  2. Neeraj Singh
    Neeraj Singh

    It is not a query caching issue. It is named_scope_caching issue. Second time sql is not being generated becuase named_scopes_cache has memoized the input data.

    @_named_scopes_cache ||= {}
    @_named_scopes_cache[method] ||= with_scope(construct_scope) { @reflection.klass.send(method, *args) }
    

    May 26th, 2010 @ 10:42 PM

  3. Neeraj Singh
    Neeraj Singh
    • Tag changed from 3.0, activerecord to 3.0, activerecord, patch, scope

    Attached is patch along with test.

    May 27th, 2010 @ 05:19 PM

  4. Neeraj Singh
    Neeraj Singh
    • Assigned user set to Pratik

    Assigning this ticket to Pratik so that he could close it. He just committed http://github.com/rails/rails/commit/517f709b51d1d2766d1a783d9f02fa... which fixes this issue.

    June 4th, 2010 @ 01:08 AM

  5. Pratik
    Pratik
    • State changed from new to resolved

    Sorry, hadn't seen this ticket/patch!

    June 4th, 2010 @ 01:16 AM