繁体   English   中英

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

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

我有一个活动记录查询,该查询在控制台中工作正常,但在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

到目前为止,您猜错了:-

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

Attendee::ActiveRecord_Relation attendees_with_sms_plans结果将与Attendee::ActiveRecord_Relation

并在调用attendees_with_sms_plans.count会导致

错误:函数计数(整数,字符变化,字符变化)不存在

这意味着Postgres不支持不止一列的count()

所以解决方案是您可以使用size()来代替count()如下所示:-

attendees_with_sms_plans.size

请通过以下查询检查功能计数是否存在

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

如果不在search_path ,则查询将找不到该函数。

要在其他架构中使用扩展,请在以下示例中将其拖放并重新创建:

DROP EXTENSION count;
CREATE EXTENSION count SCHEMA public;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM