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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With