---
title: "关于rails generate migrate 修改字段类型"
author: "夜鸣猪"
date: "2011-12-21T00:11:18Z"
tags: []
categories: ["编程语言"]
slug: "rails-generate-migrate"
draft: false
lastmod: "2011-12-22T09:53:19Z"
id: 1318699
url: "https://hlee.iteye.com/blog/1318699"
---

有几种写法，最早就是add remove了

```ruby

class AddSsl < ActiveRecord::Migration
  def up
    add_column :accounts, :ssl_enabled, :boolean, :default => 1
  end

  def down
    remove_column :accounts, :ssl_enabled
  end
end

```


这个有个显著问题，字段值没了。

那么
```ruby

rails g migration change_date_format_in_my_table


class ChangeDateFormatInMyTable < ActiveRecord::Migration
  def self.up
   change_column :my_table, :my_column, :datetime
  end

  def self.down
   change_column :my_table, :my_column, :date
  end
end


```


或者


```ruby

change_table :table_name do |t|
  t.change :column_name, :column_type, {options}
end


class ChangeDataTypeForWidgetCount < ActiveRecord::Migration
  def self.up
    change_table :widgets do |t|
      t.change :count, :float
    end
  end

  def self.down
    change_table :widgets do |t|
      t.change :count, :integer
    end
  end
end


```


还有一些


```ruby

rename_column(table_name, column_name, new_column_name)

```



```ruby

add_index(table_name, column_names, options)
add_index(:suppliers, :name)

#生成

CREATE INDEX suppliers_name_index ON suppliers(name)
add_index(:accounts, [:branch_id, :party_id], :unique => true)

#生成
CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id)

add_index(:accounts, [:branch_id, :party_id], :unique => true, :name => 'by_branch_party')


#生成

CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id)


```






```ruby


class MakeJoinUnique < ActiveRecord::Migration
  def up
    execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
  end

  def down
    execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`"
  end
end
class AddPeopleSalary < ActiveRecord::Migration
  def up
    add_column :people, :salary, :integer
    Person.reset_column_information
    Person.find(:all).each do |p|
      p.update_attribute :salary, SalaryCalculator.compute(p)
    end
  end
end

```