class AddAuthorization < ActiveRecord::Migration
  def self.up

    # This is a migration to the Object Roles Table version of the Authorization plugin
    # See http://www.writertopia.com/developers/authorization
    
    create_table "roles_users", :force => true, :id => false do |t|
      t.column :role_id,          :integer
      t.column :user_id,          :integer
      t.column :created_at,       :datetime
      t.column :updated_at,       :datetime
    end
    
    add_column :roles, :authorizable_type,  :string, :limit => 30, :default => nil
    add_column :roles, :authorizable_id,    :integer, :default => nil
    
    Role.find(:all) do |role|
      user = User.find(role.user_id)
      user.roles << role
    end
    
    remove_column :roles, :user_id
    
  end


  def self.down
    add_column :roles, :user_id, :integer, :default => nil
    
    Role.find(:all) do |role|
      role.users.each do |user|
        Role.create(:name => role.name, :user_id => user.id)
      end
      role.destroy
    end
    
    remove_column :roles, :authorizable_type
    remove_column :roles, :authorizable_id
    
    drop_table :roles_user
  end
end
