---
# System prepended metadata

title: '[rails4][migration][note]migration筆記'
tags: [Rails4, note, migration]

---

# [rails4][migration][note]migration筆記

###### tags: `Rails4`,`migration`,`note`

### 修改column預設值
https://stackoverflow.com/questions/8638079/how-to-set-default-value-to-column-in-rails-while-creating-migration

```c!
$ rails g migration change_column1_in_table_name_plural
```

migration file
```ruby
#...
change_column :table_name_plural, :column_name, :integer, :default => 0
#...
```


### 修改column type
https://tosbourn.com/rails-migrate-change-column-type/

```c!
$ rails g migration change_column1_to_be_type_in_table_name_plural
```

```ruby=
class ChangePhoneToBeStringInCustomers < ActiveRecord::Migration
  def up
    change_column :customers, :phone, :string
  end

  def down
    change_column :customers, :phone, :integer
  end
end

```



### 新增unique column或將column設為unique
https://stackoverflow.com/questions/1449459/how-do-i-make-a-column-unique-and-index-it-in-a-ruby-on-rails-migration

>語法: 
>rails generate migration add_index_to_table_name column_name:uniq
>

ex:將username設定為unique
```terminal
$ rails generate migration add_index_to_users username:uniq
```

產生migration後先**不要**執行migrate,
開啟產生的新migration檔：
```ruby
class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_column :users, :username, :string  #<--將此行註解或刪除
    add_index :users, :username, unique: true
  end
end
```

修改後再執行migrate
```terminal
$ rake db:migrate
```

>使用add_index語法產生migration檔,雖然只有add_index,migration還是會自動產生add_column,所以必須手動將該行註解或刪除
---

### 新增欄位至資料表
方1(自動增加欄位)
https://stackoverflow.com/questions/4834809/adding-a-column-to-an-existing-table-in-a-rails-migration
```c
$ rails generate migration add_fieldname_to_tablename fieldname:string
$ rake db:migrate
```

方2(手動增加欄位)
```c
$ rails generate migration add_column_name_in_table_name
```
migration檔範例
```ruby
class AddCatIdInProduct < ActiveRecord::Migration
  def change
    add_column :products, :cat_id, :integer
    add_index :products, :cat_id
  end
end

```
>migration修改完後記得執行rake db:migtrate


### 新增帶有reference的migration

https://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4
https://stackoverflow.com/questions/31843363/rails-how-to-delete-a-pending-migration/31843442


```c!
$ rails g migration addModelName1ToModelName2 ModelName1:references
$ rake db:migrate
```
>上述語法會在ModelName2所對應的table新增ModelName1_id欄位

---

### 移除尚未執行的migration
```c!
$ rails d migration migration_name_without_date_and_time
```

### 察看migration status
```c!
$ rake db:migrate:status
```

### 將已經執行過的最後一個migration倒回去
```c!
$ rake db:rollback
```

---