rails migration create view
class RecentDrivingSummariesView < ActiveRecord::Migration[5.2]
def change
reversible do |dir|
dir.up do
execute <<-SQL
CREATE OR REPLACE VIEW public.recent_driving_summaries AS
SELECT
p.id,
p.short_user_id,
nullif(p.username, '') as username,
(SELECT AVG(s.average_score_accel) FROM driver_summaries s WHERE s.short_user_id = p.short_user_id AND s.score_date >= NOW() - interval '2 week') AS average_score_accel
FROM
driver_profiles p;
SQL
end
dir.down do
execute <<-SQL
DROP VIEW IF EXISTS public.recent_driving_summaries;
SQL
end
end
end
end