简体   繁体   中英

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM