2012-06-19 215 views
6

我執行我的控制器之一以下原料SQL查詢:Ruby on Rails的 - 動態SQL查詢

active_users_query = <<-SQL 
     SELECT count(DISTINCT patients.id) 
     FROM public.patients, public.subscriptions, public.users, public.calendar_days 
     WHERE patients.user_id = users.id 
     AND patients.id = calendar_days.patient_id 
     AND subscriptions.user_id = patients.user_id 
     AND (date_trunc('day',patients.last_sync) > current_date - interval '30 days' 
     OR date_trunc('day', calendar_days.created_at) > current_date - interval '30 days' 
     OR date_trunc('day',users.current_sign_in_at) > current_date - interval '30 days') 
     AND subscriptions.code_id = 2 
SQL 

有沒有一種方法,我可以添加一些RoR的代碼來此查詢的最後一行產生code_id動態?

事情是這樣的:

AND subscriptions.code_id = '@subscription.code' 

回答

10

您可以在定界符字符串

active_users_query = <<-SQL 
     SELECT count(DISTINCT patients.id) 
     FROM public.patients, public.subscriptions, public.users, public.calendar_days 
     WHERE patients.user_id = users.id 
     AND patients.id = calendar_days.patient_id 
     AND subscriptions.user_id = patients.user_id 
     AND (date_trunc('day',patients.last_sync) > current_date - interval '30 days' 
     OR date_trunc('day', calendar_days.created_at) > current_date - interval '30 days' 
     OR date_trunc('day',users.current_sign_in_at) > current_date - interval '30 days') 
     AND subscriptions.code_id = '#{@subscription.code}' 
SQL 
+0

工作就像一個魅力插值Ruby的變量。謝謝 !! – Myxtic