This project is archived and is in readonly mode.

#263 ✓invalid
Ryan Bates

calling named scope in class method

Reported by Ryan Bates | May 27th, 2008 @ 04:21 PM

When a named scope is called inside a class method, it loses the other scopes in the chain. For example:

class Topic < ActiveRecord::Base
  named_scope :approved, :conditions => {:approved => true}
  named_scope :replied, :conditions => ['replies_count > 0']

  def self.approved_through_class_method

Topic.replied.approved_through_class_method # => loses replied scope

What's interesting is that if I append "all" to the approved call in the class method then it will work.

def self.approved_through_class_method

Topic.replied.approved_through_class_method # => keeps replied scope

I have attached a failing test, but I'm not familiar enough with named_scope to make it pass.

Comments and changes to this ticket

  • josh

    josh July 17th, 2008 @ 01:59 AM

    • Assigned user set to “Pratik”
    • Tag set to bug, named_scope, tested
  • Pratik

    Pratik July 18th, 2008 @ 03:02 AM

    • State changed from “new” to “invalid”

    This would happen because you're calling approved_through_class_method on Scope object. In case of Topic.replied.approved, Scope#method_missing checks @@scopes hash to see if :approved is a named scope or not. Wherein case of Topic.replied.approved_through_class_method, there is no way to determine if approved_through_class_method is going to return a named scope or not.

    The real solution to this would be very fugly and in no way not worth it.

    So the practical solution : Define the method in named scope extension.

      named_scope :replied, :conditions => ['replies_count > 0'] do
        def approved_through_class_method

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>

People watching this ticket