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.

Class methods which call named_scopes lose previous scope (both associations and other scopes)

#1907

ActiveRecord models' class methods get added to collections (keeping scope):


    class Post < AR::B
  
      belongs_to :user
    
      def self.wadus
        find(:all, :conditions => { :wadus => "wadus" })
      end
    
    end
  
    user.posts.wadus
    # SELECT * FROM "posts" WHERE ("posts"."wadus" = 'wadus') AND ("posts".user_id = 1)

This works also for named_scopes:


    class Post
      named_scope :starting_with_a, {:conditions => "name LIKE 'a%'"}
    end
  
    Post.starting_with_a.wadus
    # SELECT * FROM "posts" WHERE ("posts"."wadus" = 'wadus') AND (name LIKE 'a%')

But this behaviour breaks if your class method calls one or more named scope:


    class Post < ActiveRecord::Base
  
      belongs_to :user
  
      named_scope :starting_with_a, {:conditions => "name LIKE 'a%'"}  
      named_scope :ending_with_a, {:conditions => "name LIKE '%a'"}
  
      def self.calls_named_scope
        ending_with_a
      end
  
    end
  
    Post.starting_with_a.calls_named_scope
    # SELECT * FROM "posts" WHERE (name LIKE '%a') # loses "name LIKE 'a%'" (from starting_with_a)
    user.posts.calls_named_scope
    # SELECT * FROM "posts" WHERE (name LIKE '%a') # loses "user_id = 1" (from association)

Attached patch includes tests showing this behaviour.

Reported by porras · February 7th, 2009 @ 06:42 PM

State: resolved
Milestone: 2.x
Assigned to: Pratik Pratik
Importance: none

Activity

  1. Luismi Cavallé
  2. Luismi Cavallé
    Luismi Cavallé
    • Tag changed from activerecord, bug, named_scope to activerecord, bug, named_scope, patch, tested

    Patch contributed by Luismi Cavallé, Sergio Gil and Fernando Guillén from Madrid Hackathon.

    February 7th, 2009 @ 08:03 PM

  3. Guillermo Álvarez
  4. jjggss
  5. Guillermo Álvarez
  6. Pratik
    Pratik
    • Assigned user set to Pratik
    • State changed from new to resolved

    Looks like this has been resolved. Please post here if it's still a problem and I'll reopen.

    Thanks.

    March 9th, 2009 @ 01:37 PM