Rails Migration 可用的方法

在上述change方法里,我们有以下方法可以使用:

对资料表做修改:

create_table(name, options) 新增资料表
drop_table(name) 移除资料表
rename_table(old_name, new_name) 修改资料表名称
change_table 修改资料表栏位

个别修改资料表栏位:

add_column(table, column, type, options) 新增一个栏位
rename_column(table, old_column_name, new_column_name) 修改栏位名称
change_column(table, column, type, options) 修改栏位的型态(type)
remove_column(table , column) 移除栏位

新增、移除索引:

add_index(table, columns, options) 新增索引
remove_index(table, index) 移除索引
options 可为空,或是:unique => true表示这是唯一。

新增、移除外部键限制:

add_foreign_key(from_table, to_table, options)
remove_foreign_key(from_table, to_table, options)
options 可为空,或是可自定:column => from_table_foreign_key_column (预设是{to_table}_id)和:primary_key => to_table_primary_key_column(预设是id)。

新增和移除 Table

执行 rails g model 时,Rails就会顺便新增对应的 Migration 档案。以上一章产生的categories migration为例:

class CreateCategories < ActiveRecord::Migration[5.1]
    def change
        create_table :categories do |t|
          t.string :name
          t.integer :position
          t.timestamps
        end

        add_column :events, :category_id, :integer
        add_index :events, :category_id
    end
end

其中的 timestamps 会建立叫做 created_at 和 updated_at 的时间栏位,这是Rails的常用惯例。它会自动设成资料新增的时间以及会後更新时间。

修改 Table

我们来试着新增一个栏位吧:

rails g migration add_description_to_categories
打开 db/migrate/20110411163049_add_description_to_categories.rb

class AddDescriptionToCategories < ActiveRecord::Migration[5.1]
  def change
    add_column :categories, :description, :text
  end
end

完成後,执行 rails db:migrate便会实际在资料库新增这个栏位。

参考资料

[Rails 实战圣经] https://ihower.tw/rails/migrations.html


<<:  Day 7 ( 入门 ) 爱心呼吸灯

>>:  Day 7 图片去背 ( 遮罩 )

为了转生而点技能-JavaScript,day14(this下篇: Call、apply呼叫及bind

Call呼叫:呼叫函式的方法,并且能指定 this 值。 用法:函式名.call(指定的this变数...

资料库连线设定

连线资料库 Laravel 关於资料库连线的设定写在 config\database.php 中,来...

27.Copmuted vs Watcher

一般情况下,使用 computed 比起 watcher 更简洁,如下: new Vue({ dat...

Day07 X Image Sprites

经过昨天的一番折腾,我想读者们都对基本的图片优化稍有概念了,今天要介绍的优化技巧其实严格来说也算是...

[Day 16] IOCP Input/Output Completion Port

前言 今天要聊到 IOCP 也是一种非同步 IO 的处理方案, 是由 windows 提供的, 而昨...