17

I am getting this error while accessing scopes.

Here is AR model

class StatisticVariable < ActiveRecord::Base
  attr_accessible :code, :name

  has_many  :statistic_values

  scope :logins, where(code: 'logins').first
  scope :unique_logins, where(code: 'unique_logins').first
  scope :registrations, where(code: 'registrations').first

end

and when I try with StatisticVariable.logins or any other scopes it gives:

NoMethodError: undefined method `default_scoped?'

If I configure scope as class method then it works perfectly.

def self.registrations
    where(code: 'registrations').first
end

Please guide me to understand and fix this problem.

zishe
  • 10,665
  • 12
  • 64
  • 103
Amit Patel
  • 15,609
  • 18
  • 68
  • 106

2 Answers2

29

Your so called scopes are not scopes: they aren't chainable.

I guess Rails tries to append a potential default_scope to your result which leads to failure.

Do something like:

  scope :logins, where(code: 'logins')
  scope :unique_logins, where(code: 'unique_logins')
  scope :registrations, where(code: 'registrations')

  def self.login
    logins.first
  end
zishe
  • 10,665
  • 12
  • 64
  • 103
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Ah, thanks for this! I got this when changing `default_scope order: "foo"` to `default_scope { { order: "foo" } }`. Fixed it by changing it to `default_scope { order("foo") }`. – Henrik N Feb 27 '15 at 09:47
0

I got this error because one of my scopes was returning self, which I assumed was the relation object (didn't work); returning nil instead achieved the expected result. eg:

scope :except_ids, -> ids do
  if ids.present?
    ids = ids.split(',') if ids.respond_to?(:split)
    where('id not in (?)', ids)
  end
end

if ids.present? returns false, the condition returns nil and the scope has no effect, but is still chainable.

Steven Soroka
  • 19,404
  • 4
  • 52
  • 40