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.

calling named scope in class method

#263

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
    approved
  end
end

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
  approved.all
end

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.

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

State: invalid
Milestone: none
Assigned to: Pratik Pratik
Importance: none

Activity

  1. josh
    josh
    • Assigned user set to Pratik
    • Tag set to bug, named_scope, tested

    July 17th, 2008 @ 01:59 AM

  2. Pratik
    Pratik
    • 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
          approved
        end
      end
    

    July 18th, 2008 @ 03:02 AM