This project is archived and is in readonly mode.

#4219 ✓resolved
Andrew White

Add column and index query methods to ActiveRecord::Schema

Reported by Andrew White | March 18th, 2010 @ 05:21 PM | in 3.0.2

The attached patch adds two methods to the ActiveRecord::Schema format - column_exists? and index_exists?

The use case for this feature is to make it easier for plugin/engine developers to create migrations that can cope with a database in an indeterminate state. e.g:

class MyEngineCreateUsers < ActiveRecord::Migration
  def self.up
    if table_exists?(:users)
      # Traditional style
      add_column(:users, :remember_token, :string, :limit => 128) unless column_exists?(:users, :remember_token)
      add_index(:users, :remember_token) unless index_exists?(:users, :remember_token)

      # Sexy style
      change_table(:users) do |t|
        t.string(:confirmation_token, :limit => 128) unless t.column_exists?(:confirmation_token)
        t.boolean(:email_confirmed, :default => false, :null => false) unless t.column_exists?(:email_confirmed)
        t.index([:id, :confirmation_token]) unless t.index_exists?([:id, :confirmation_token])
      end
    else
      create_table(:users) do |t|
        t.string   :email
        t.string   :encrypted_password, :limit => 128
        t.string   :salt,               :limit => 128
        t.string   :confirmation_token, :limit => 128
        t.string   :remember_token,     :limit => 128
        t.boolean  :email_confirmed, :default => false, :null => false
        t.timestamps
      end

      add_index :users, [:id, :confirmation_token]
      add_index :users, :email
      add_index :users, :remember_token
    end
  end

  def self.down
    drop_table :users
  end
end

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages