Skip to content

Instantly share code, notes, and snippets.

@jaimerson
Created August 1, 2016 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaimerson/6e7f5ef709d6c09c6525b44773b078f7 to your computer and use it in GitHub Desktop.
Save jaimerson/6e7f5ef709d6c09c6525b44773b078f7 to your computer and use it in GitHub Desktop.
First approach at creating view
class CreateBikesReportView < ActiveRecord::Migration
def change
reversible do |dir|
dir.up do
execute(
<<-QUERY
CREATE MATERIALIZED VIEW bikes_reports AS
SELECT
bikes.name, bikes.model,
count(rentals.id) as times_rented,
round(SUM(extract(
epoch from (rentals.returned_at - rentals.created_at)
)/ 3600 * bikes.price)::numeric, 2) as revenue
FROM
rentals INNER JOIN bikes ON bikes.id = rentals.bike_id
GROUP BY bikes.id
ORDER BY times_rented DESC;
QUERY
)
end
dir.down do
execute(
<<-QUERY
DROP MATERIALIZED VIEW IF EXISTS bikes_reports;
QUERY
)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment