This project is archived and is in readonly mode.

#1960 ✓resolved
Diego Algorta

Make named_scopes remember the current scope when defined

Reported by Diego Algorta | February 13th, 2009 @ 07:40 AM | in 2.x

Given the following code:

class Post < ActiveRecord::Base
  belongs_to :topic
  belongs_to :author

  named_scope :published, :conditions => {:published => true}
  named_scope :by_author, lambda {|a| {:conditions => {:author_id =>}}}
  named_scope :ranked, :order => "posts.rank DESC"
  named_scope :limit, lambda {|limit| {:limit => limit}}

  def self.top_by(an_author)

class Topic < ActiveRecord::Base
  has_many :posts

class Author < ActiveRecord::Base
  has_many :posts

Without this patch, @topic.posts.top_by(@author) generates the exact same query than Post.top_by(@author), totally ignoring the scope added by the has_many :posts in Topic. That's because that scope is being removed from the stacked scopes after the top_by execution where the chained scopes where defined, but before the chained scopes are really executing thus firing the Scope#load_found call.

With this patch, the current scope is saved in the Scope instance at instantiation time, so it can be re-applied when executed.

Comments and changes to this ticket

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>


Referenced by