Using scope (after where) in the model resets where condition

Viewed 168

I have a very strange behavior of Rails 5.2 and ruby 2.6

A different sequence of method chaining gives different results.

Example #1

Erp::Packing::Session::ZonePicker.where(round_id: 3084).active.to_sql

gives:

SELECT \"erp_packing_sessions\".* 
FROM \"erp_packing_sessions\" 
WHERE (logged_out_at IS NULL)
 AND (started_at > '2021-01-27 23:00:00')

and the scope is:

scope :active, -> { not_logged_out.where('started_at > ?', Time.current.beginning_of_day) }

scope :not_logged_out, -> { where('logged_out_at IS NULL') }

In this example where condition is lost.

Example #2 I put scope first and then where condition:

Erp::Packing::Session::ZonePicker.active.where(round_id: 3084).to_sql

gives:

SELECT \"erp_packing_sessions\".* 
FROM \"erp_packing_sessions\" 
WHERE (logged_out_at IS NULL) 
  AND (started_at > '2021-01-27 23:00:00') 
  AND \"erp_packing_sessions\".\"round_id\" = 3084

This example works as expected.

We are migrating from rails 4.2 to 5.2 and getting this strange behaviour.

Could you please point out what could be the reason and if that is covered in the documentation?

Small update: interesting, if I write it as a method:


  def self.activated
    where('started_at > ?', Time.current.beginning_of_day).where('logged_out_at IS NULL')
  end

it works as expected.

Update 2: Erp::Packing::Session::ZonePicker is the subclass of Erp::Packing::Session::Base where the scopes are defined. Thus could be related to this question: inheritance of scopes

Update 3: Also, Erp::Packing::Session::ZonePicker.where(round_id: 3084).method(:active).source =>

def #{method}(*args, &block)
  scoping { @klass.#{method}(*args, &block) }
end

Does @klass.#{method} mean that it’s calling the scope on the class rather chaining?

0 Answers
Related