我有一个活动记录查询,它在控制台中运行良好,但在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

最佳答案

好吧,就猜错了:-

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将导致
错误:函数计数(整数、字符变化、字符变化)
不存在
也就是说Postgres does not support count()with more than one column
所以解决方案是,如果size()像这样,您可以使用count():-
attendees_with_sms_plans.size

09-15 22:17