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.

named_scope doesn't work when 2 procs expect arguments

#1174

Mixing 2 named_scopes that accepts arguments raises the following error depending on the order that the scopes are executed:

ArgumentError: wrong number of arguments (2 for 0)
 from (__DELEGATION__):2:in `sort_by'
 from (__DELEGATION__):2:in `__send__'
 from (__DELEGATION__):2:in `sort_by'
 from (irb):1

This will work:


User.sort_by(:name, :desc).by_country('us')

But this won't:


User.by_country('us').sort_by(:name, :desc)

Here's what the model looks like:


class User < ActiveRecord::Base
  named_scope :sort_by, Proc.new { |attr, order|
    order ||= 'asc'
    {:order => "#{attr} #{order}"}
  }

  named_scope :by_country, Proc.new { |code|
    {:conditions => {:country_code => code.to_s}}
  }
end

Reported by Nando Vieira · October 4th, 2008 @ 07:01 PM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Frederick Cheung
    Frederick Cheung
    • Tag changed from activerecord, block, bug, named_scope, proc to activerecord, block, bug, edge, named_scope, proc

    Is the problem that sort_by scope you've defined is being (in some cases) shadowed by the built in sort_by method on arrays ? (ie if you change it to order_by then does it work ?)

    December 10th, 2008 @ 01:24 PM

  2. Frederick Cheung
    Frederick Cheung
    • State changed from new to invalid

    A quick experiment reveals that to be the case. Change sort_by to order_by and you're good to go.

    December 21st, 2008 @ 11:10 AM

  3. Nando Vieira
    Nando Vieira

    Make sense... I didn't remember the sort_by method. :/

    December 21st, 2008 @ 11:18 AM