如何在`find_by_sql`中传递字符串值

时间:2016-10-16 11:48:54

标签: ruby-on-rails ruby-on-rails-4 find-by-sql

使用类似的查询:

Campaign.find_by_sql("select c.*,sc.*,org.name as org_name from campaigns as c left join super_campaigns as sc ON sc.id= c.super_campaign_id left join organisations as org ON org.id= c.organisation_id where c.status=0 AND sc.status='active'")

使用sc.status='active'后出错。谢谢。

1 个答案:

答案 0 :(得分:1)

你可以通过使用插值来实现这一点,这里是我为做类似事情而做的项目的一个例子

self.find_by_sql("SELECT s.subject_title  AS subject_name,s.subject_code AS subject_code,
COUNT(*) AS total_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::HIGH}'        THEN 1 END) AS high_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::NORMAL}' THEN 1 END) AS normal_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::LOW}'     THEN 1 END) AS low_complaints
FROM
tickets AS t
JOIN
subjects AS s
ON  t.subject_id = s.id
JOIN
priorities AS p
ON t.priority_id = p.id
WHERE
p.priority_name IN ('#{Ticket::HIGH}', '#{Ticket::NORMAL}', '#{Ticket::LOW}')
GROUP BY s.subject_title, s.subject_code
ORDER BY total_complaints ASC")

正如您所看到的,#{Ticket::HIGH}来自PRIORITY = [HIGH = 'high', NORMAL = 'normal', LOW = 'low']来自其他人

注意:这是原始代码的一部分。