本文介绍了未定义的方法“default_scoped?"在访问范围时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在访问范围时收到此错误.

I am getting this error while accessing scopes.

这是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 或它给出的任何其他范围时:

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.

推荐答案

你所谓的 scopes 不是作用域:它们不可链接.

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

我猜 Rails 试图将潜在的 default_scope 附加到您的结果中,这会导致失败.

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

做类似的事情:

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

  def self.login
    logins.first
  end

这篇关于未定义的方法“default_scoped?"在访问范围时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 18:56