Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

ruby on rails - Using scope (after where) in the model resets where condition

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?

question from:https://stackoverflow.com/questions/65936801/using-scope-after-where-in-the-model-resets-where-condition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...