【问题标题】:undefined method `default_scoped?' while accessing scope未定义的方法“default_scoped?”在访问范围时
【发布时间】:2012-09-11 07:51:47
【问题描述】:

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

这是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?'

如果我将作用域配置为类方法,那么它可以完美地工作。

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

请指导我理解并解决这个问题。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord named-scope


    【解决方案1】:

    您所谓的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") } 来修复它。
    【解决方案2】:

    我收到此错误是因为我的一个作用域返回了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,范围无效,但仍可链接。

    【讨论】:

      猜你喜欢
      • 2012-01-18
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多