如何在 rake 任务中获取在 Rails 控制台中工作的 Active Record 查询?

How do I get Active Record query that works in Rails console working in a rake task?

我有一个活动记录查询,它在控制台中运行良好,但在 rake 任务中使用它时不起作用

这是我的 rake 任务的开始:

namespace :attendees do
  desc "Migrate sms plans to receive_sms attribute for attendees"
  task migrate_sms_plans: :environment do
    attendees_with_sms_plans = Attendee.select('attendees.id, attendees.phone, attendees.local_phone').joins(:plans).where('plans.name = ?', "Yes! SMS!")

为什么 select 语句在我的 rails 控制台中有效,但在 rake 任务中使用它时出现以下错误,我该如何解决:

ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR:  function count(integer, character varying, character varying) does not exist
LINE 1: SELECT COUNT(attendees.id, attendees.phone, attendees.local_...
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

原来错误不是 select 语句,而是在下一行:

puts <<-TEXT
    Going to migrate #{attendees_with_sms_plans.count} attendees from "Yes! SMS!" plan to receive_sms: true attribute on Attendee Model
TEXT

我修改为:

puts <<-TEXT
    Going to migrate #{attendees_with_sms_plans.to_a.count} attendees from "Yes! SMS!" plan to receive_sms: true attribute on Attendee Model
TEXT

请使用以下查询检查函数计数是否存在

SELECT n.nspname
FROM pg_extension e
   JOIN pg_namespace n
      ON e.extnamespace = n.oid
WHERE e.extname = 'count';

如果您的 search_path 中没有该函数,您的查询将找不到该函数。

要在不同的架构中使用扩展,在以下示例中 public,删除并重新创建它:

DROP EXTENSION count;
CREATE EXTENSION count SCHEMA public;

好吧就猜错了:-

attendees_with_sms_plans = Attendee.select('attendees.id, attendees.phone, attendees.local_phone').joins(:plans).where('plans.name = ?', "Yes! SMS!")

attendees_with_sms_plans 将结果为 Attendee::ActiveRecord_Relation

调用 attendees_with_sms_plans.count 将导致

ERROR: function count(integer, character varying, character varying) does not exist

这意味着

所以解决方案是如果 count() 像这样,您可以使用 size() 代替:-

attendees_with_sms_plans.size