undefined方法`default_scoped?’ 在访问范围时

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

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

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

您所谓的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 

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