Allows database views to be stored as sql files and be easily applyable
Just add following line to your Gemfile
gem 'activerecord-database-views'and run bundle install
Place your SQL that view will be generated from into db\views directory (The actual view name will be the same as file name), i.e.
-- db\views\reverse_users.sql
SELECT * FROM users ORDER BY users.id DESCThen run console (console c) and execute...
ActiveRecord::DatabaseViews.reload!...to reload all defined views.
You can test them out by
ActiveRecord::Base.connection.execute('SELECT * FROM reverse_users').to_aor just attach them to a model file
class ReverseUser < ActiveRecord::Base
endand run
ReverseUser.allThis is sometimes necessary in case of some changing migrations
ActiveRecord::DatabaseViews.without do
# some code that has to be executed with views dropped
enddiscriminate_class_for_record to the rescue :)
class ReverseUser < ActiveRecord::Base
private
def self.discriminate_class_for_record(record)
User
end
endAdd new file hooks.rake under lib\tasks and copy following code
db_tasks = %w[db:migrate db:rollback db:schema:load]
namespace :reload_views do
db_tasks.each do |task_name|
task task_name => %w[environment db:load_config] do
ActiveRecord::DatabaseViews.reload!
end
end
end
db_tasks.each do |task_name|
Rake::Task[task_name].enhance do
Rake::Task["reload_views:#{task_name}"].invoke
end
endAs a bonus you will be able to reload views using rake task as well, i.e. rake reload_views:db:migrate
