ActiveRecord.where在rake任务中无效,可在Rails控制台中使用

问题描述

我已将此rake任务设置为每3分钟通过Cloud66作业在生产服务器上运行。目的是释放对在结帐期间被放弃的预订所做的预订。该作业运行成功,但是作为rake任务运行时无效。

namespace :order do
  desc "Unreserves bookings that have had no activity for 5 minutes"
  task release_abandoned_bookings: :environment do
    abandoned_bookings = PhysicalBookingBase.where("reserved = true AND state IN (?) AND updated_at < ?",['personal_data','awaiting_payment'],5.minutes.ago)
    abandoned_bookings.update_all(reserved:false)
    puts "Released #{abandoned_bookings.count} abandoned bookings" # = Released 0 abandoned bookings
  end

当我SSH进入服务器并运行bundle exec rake order:release_abandoned_bookings

时,此效果相同

但是,如果我使用ssh进入服务器,请复制/粘贴两条基本行,并在rails控制台中运行它们,它们将执行应做的事情:

pry(main)> abandoned_bookings = PhysicalBookingBase.where("reserved = true AND state IN (?) AND updated_at < ?",5.minutes.ago)
  PhysicalBookingBase Load (17.1ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."type" IN ($1,$2,$3) AND (reserved = true AND state IN ('personal_data','awaiting_payment') AND updated_at < '2020-10-30 15:41:45.986908')  [["type","PhysicalBookingBase"],["type","OrganizationBooking"],"Booking"]]
=> [#<OrganizationBooking id: 39578,reserved: true,state: "personal_data",updated_at: "2020-10-30 15:08:19">]
​
[3] pry(main)> abandoned_bookings.update_all(reserved:false)
  PhysicalBookingBase Update All (18.7ms)  UPDATE "bookings" SET "reserved" = $1 WHERE "bookings"."type" IN ($2,$3,$4) AND (reserved = true AND state IN ('personal_data','awaiting_payment') AND updated_at < '2020-10-30 15:41:45.986908')  [["reserved",false],"Booking"]]
=> 1
​
[4] pry(main)> PhysicalBookingBase.where("reserved = true AND state IN (?) AND updated_at < ?",5.minutes.ago)
  PhysicalBookingBase Load (16.3ms)  SELECT "bookings".* FROM "bookings" WHERE "bookings"."type" IN ($1,'awaiting_payment') AND updated_at < '2020-10-30 15:41:56.885991')  [["type","Booking"]]
=> []

解决方法

解决了。原来,这是与STI相关的问题。由于SELECT date,type,left(value,40) as value FROM my.data 是中介基类,当它作为rake任务运行时,它永远不会找到任何记录。数据库中没有记录在PhysicalBookingBase字段中具有“ PhysicalBookingBase”。

TL; DR 解决方案是在查找预订时使用type字段为条件的BookingBase作为谓词的基础。

STI层次结构如下:

  • type继承自PhysicalBookingBase,后者引用了表名。
  • BookingBase和在表的Booking列中具有表示形式的其他变体继承自type
  • 此外,我们还有PhysicalBookingBase继承自DigitalBookingBase,它遵循相同的结构

出于某种原因,在Rails应用程序或Rails控制台中运行时,使用BookingBase作为谓词的基础可以很好地工作,但是在rake运行同一行代码时则不能。我什至尝试添加officially suggested STI Preload module,但这也无济于事。