undefined method `default_scoped?' while accessing scope

前端 未结 2 472
轻奢々
轻奢々 2020-12-18 20:50

I am getting this error while accessing scopes.

Here is AR model

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

  ha         


        
相关标签:
2条回答
  • 2020-12-18 21:07

    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
    
    0 讨论(0)
  • 2020-12-18 21:07

    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.

    0 讨论(0)
提交回复
热议问题