Skip to content

Instantly share code, notes, and snippets.

@yui-knk
Last active September 5, 2015 15:40
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 yui-knk/1c5d3cb7bb8571c1e3b7 to your computer and use it in GitHub Desktop.
Save yui-knk/1c5d3cb7bb8571c1e3b7 to your computer and use it in GitHub Desktop.

rails adapter * tables * view

rails 4276b214f8a13a38ac7dc4911e90d295a8e40d5a

books is table, ebooks is view

class MigrationA < ActiveRecord::Migration
  def change
    create_table :books, force: true do |t|
      t.integer :author_id
      t.string :format
      t.column :name, :string
      t.column :status, :integer, default: 0
      t.column :read_status, :integer, default: 0
      t.column :nullable_status, :integer
      t.column :language, :integer, default: 0
      t.column :author_visibility, :integer, default: 0
      t.column :illustrator_visibility, :integer, default: 0
      t.column :font_size, :integer, default: 0
    end
  end
end

class MigrationB < ActiveRecord::Migration
  def create_view(name, query)
    execute "CREATE VIEW #{name} AS #{query}"
  end

  def change
    create_view "ebooks", <<-SQL
      SELECT id, name, status FROM books WHERE format = 'ebook'
    SQL
  end
end

pg

[2] pry(main)> ActiveRecord::Base.connection.tables
=> ["schema_migrations", "books"]
[3] pry(main)> ActiveRecord::Base.connection.table_exists? :ebooks
=> true

mysql2

[5] pry(main)> ActiveRecord::Base.connection.tables
=> ["books", "ebooks", "schema_migrations"]
[6] pry(main)> ActiveRecord::Base.connection.table_exists? :ebooks
=> true

sqlite

[2] pry(main)> ActiveRecord::Base.connection.tables
=> ["schema_migrations", "books", "ebooks"]
[3] pry(main)> ActiveRecord::Base.connection.table_exists? :ebooks
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment