访问作用域时出现undefined method 'default_scoped?'错误

17

在访问作用域时,我遇到了这个错误。

以下是AR模型

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

当我尝试使用StatisticVariable.logins或任何其他作用域时,它会出现:

NoMethodError: undefined method `default_scoped?'

如果我将范围(scope)配置为类方法(class method),那么它就能完美地工作。

def self.registrations
    where(code: 'registrations').first
end
请指导我理解并解决这个问题。
2个回答

29

你所谓的scopes并不是真正的作用域,因为它们不能够进行链式操作。

我猜Rails尝试在你的结果中附加一个可能的default_scope,这导致了失败。

像这样做:

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

  def self.login
    logins.first
  end

啊,谢谢你!我在将 default_scope order: "foo" 更改为 default_scope { { order: "foo" } } 时遇到了这个问题。通过将其更改为 default_scope { order("foo") },我已经解决了它。 - Henrik N

0
我之前遇到了一个错误,因为我的某个作用域返回了 self,我以为它是关联对象(但是并没有起作用);而返回 nil 则达到了预期的结果。例如:
scope :except_ids, -> ids do
  if ids.present?
    ids = ids.split(',') if ids.respond_to?(:split)
    where('id not in (?)', ids)
  end
end

如果ids.present?返回false,条件返回nil,范围没有效果,但仍然可以链式调用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接