Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Dynamic SQL Query

I am executing the following raw sql query in one of my controllers :

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

Is there a way I can add some RoR code to the last line of this query to generate the code_id dynamically ?

Something like this :

AND subscriptions.code_id = '@subscription.code'
like image 726
Myxtic Avatar asked Jun 19 '12 16:06

Myxtic


1 Answers

You can interpolate Ruby variables in heredoc strings

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
like image 143
dimuch Avatar answered Nov 10 '22 00:11

dimuch