Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ActiveRecord View Migrations

Rake task to perform "view migrations" for using SQL Views with Rails. Avoids the need to copy or re-run multiple migrations when changes are made to queries providing view data.

Usage: rake db:views:load

Place SQL create statement for each view in a file as db/views/<view_name>.sql. Optionally include a numeric prefix such as 01_first_view.sql to order views that may have dependencies.

namespace :db do
  namespace :views do
    desc "Execute all stored View statements on DB connection"
    task :load => :environment do
      ActiveRecord::Base.establish_connection(ENV['RAILS_ENV'])
      
      views = Dir.glob("#{Rails.root.join('db', 'views')}/*")

      # First, drop all of the views the hard way
      views.each do |view|
        view_name = File.basename(view, '.sql').gsub(/^\d+_/, '')
        ActiveRecord::Base.connection.execute("DROP VIEW IF EXISTS #{view_name} CASCADE;")
      end

      # And now execute the create statements
      views.each do |view|
        view_name = File.basename(view, '.sql').gsub(/^\d+_/, '')
        sql = IO.read(Rails.root.join('db', 'views', view))
        ActiveRecord::Base.connection.execute(sql)
        puts "Created database view for #{view_name}"
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.