Thursday, January 27, 2011

Rails SQL Views

Getting started

The Rails SQL Views extension modifies some of the modules in ActiveRecord to add support for SQL Views. It adds the methods create_view and drop_view to the AbstractAdapter so you can use these in migrations. It also modifies the SchemaDumper class to support dumping of create_view logic. Currently the following adapters are supported:
  • MySQL
  • PostgreSQL (native and pure ruby)
  • SQL Server
  1. Get It

    There are several ways to get the Rails SQL Views extension:
    Install the Gem
    Get to your command line and type sudo gem install rails_sql_views on Linux or OS X or type gem install rails_sql_views on Windows. Rails SQL Views depends on ActiveRecord. If necessary you may have to approve the installation of these dependencies if they are not already installed.
    Download
    You can also download the packages in Zip, Gzip, or Gem format from the ActiveWarehouse files section on RubyForge.
    Github Clone
    For the brave you can get the latest code from the Github repository: git clone git://github.com/aeden/rails_sql_views.git.





  2. Require Statements

    Add the following to your config/environment.rb:
    require 'rubygems'
    require 'rails_sql_views'



  3. Use It!

    You can now use the library:
    class CreatePersonView < ActiveRecord::Migration
        def self.up
          create_view :v_people, "select * from people" do |t|
            t.column :id
            t.column :name
            t.column :social_security
          end
        end
    
        def self.down
          drop_view :v_people
        end
      end



What's There Now?

Right now the library does the following:
  • Adds create_view and drop_view methods to Rails schema code
  • Makes ActiveRecord::SchemaDumper view-aware
  • Adds a supports_views? abstract method to ActiveRecord::ConnectionAdapters::AbstractAdapter which returns false by default
  • Changes the MySQL connection adapter to use SHOW TABLE STATUS rather than SHOW TABLES, so that the tables method returns only tables. Views are returned through the views method
  • Implements view support for MySQL, PostgreSQL and SQL Server
  • Unit tests included
http://activewarehouse.rubyforge.org/rails_sql_views/
http://stackoverflow.com/questions/3137192/creating-migrations-for-sql-views-in-rails-with-boolean-values

    No comments: