Activerecord:如何使用find_by_sql进行查询并包含变量

时间:2014-12-09 14:29:24

标签: sql ruby-on-rails postgresql activerecord

我试图使用activerecords的find_by_sql从3个表中查询

date = '2014-12-14'
bills_with_sms = ActualBill.find_by_sql("SELECT * FROM users u LEFT JOIN bills b ON u.id=b.user_id LEFT JOIN actual_bills ab ON b.id= ab.bill_id WHERE u.total_sms_count > 0 AND b.want_sms= true AND  date = ANY (ab.sms_reminder_schedule) AND ab.paid = false AND b.active = true")

但是在运行此代码时,它将显示此错误消息

PG::UndefinedColumn: ERROR:  column "date" does not exist
LINE 1: ...E u.total_sms_count > 0 AND b.want_sms= true AND  date = ANY...

我尝试使用rails控制台调试,如果我将日期更改为" 2014-12-14"它将提供正确的查询,因此代码将

bills_with_sms = ActualBill.find_by_sql("SELECT * FROM users u LEFT JOIN bills b ON u.id=b.user_id LEFT JOIN actual_bills ab ON b.id= ab.bill_id WHERE u.total_sms_count > 0 AND b.want_sms= true AND  '2014-12-14' = ANY (ab.sms_reminder_schedule) AND ab.paid = false AND b.active = true")

有人可以告诉我从数组查询的正确方法是什么? sms_reminder_schedule是一个字符串数组。我想查找当天安排短信的账单。

感谢

1 个答案:

答案 0 :(得分:0)

SELECT * FROM users u LEFT JOIN bills b ON u.id=b.user_id LEFT JOIN actual_bills ab ON b.id= ab.bill_id WHERE u.total_sms_count > 0 AND b.want_sms= true AND '#{date}' = ANY (ab.sms_reminder_schedule) AND ab.paid = false AND b.active = true

这里发生的是PG无法找到列日期,我认为日期是您尝试与变量中定义的ANY比较匹配的表达式{ {1}}

您可以像Marek建议的那样使用字符串插值,例如date