rails 指南总结(二)——Model之Active Record 迁移

1.数据库迁移是什么?

  • 迁移是 Active Record 的一个特性,允许我们按时间顺序管理数据库模式。
  • Active Record 知道如何沿着时间线更新数据库模式,使其从任何历史版本更新为最新版本。
  • 有了迁移,就不必再用纯 SQL 来修改数据库模式,而是可以使用简单的 Ruby DSL 来描述对数据表的修改。
  • Active Record 还会更新 db/schema.rb 文件,以匹配最新的数据库结构。
    例:
class CreateProducts < ActiveRecord::Migration[5.0]
  def change
    create_table :products do |t|
      t.string :name
      t.text :description
 
      t.timestamps
    end
  end
end

这个迁移用于添加 products 数据表,数据表中包含 name 字符串字段和 description 文本字段。同时隐式添加了 id 主键字段,这是所有 Active Record 模型的默认主键。timestamps 宏添加了 created_at 和 updated_at 两个字段。

2. 迁移的创建

2.1 创建独立的迁移

2.1.1 创建数据表

命令:rails g migration CreateTableBlogs title:string content:string

class CreateTableBlogs < ActiveRecord::Migration[6.0]
  def change
    create_table :table_blogs do |t|
      t.string :title
      t.string :content
    end
  end
end

修改数据表 change_table

change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code
end

2.1.2 创建联结数据表

rails g migration CreateJoinTableUserBlog user blog

class CreateJoinTableUserBlog < ActiveRecord::Migration[6.0]
  def change
    create_join_table :users, :blogs do |t|
      # t.index [:user_id, :blog_id]
      # t.index [:blog_id, :user_id]
    end
  end
end

联结数据表的名称默认由 create_join_table 方法的前两个参数按字母顺序组合而来。
上面的代码会创建包含 user_id 和 blog_id 字段的 blogs_users 数据表
修改表名

create_join_table :users, :blogs, table_name: :categorization

2.1.3 增加单个字段

命令rails g migration AddEmailToUsers email:string
上面的命令会创建迁移文件20200829071554_add_email_to_users.rb

class AddEmailToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :email, :string
  end
end

2.1.4 增加多个字段

命令:rails g migration AddDeatilToUsers adress:string sex:string

class AddDeatilToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :adress, :string
    add_column :users, :sex, :string
  end
end

2.1.5 增加 references 字段

rails generate migration AddUserRefToBlogs user:references

class AddUserRefToBlogs < ActiveRecord::Migration[6.0]
  def change
    add_reference :blogs, :user, null: false, foreign_key: true
  end
end

这个迁移会创建 user_id 字段并添加索引`

2.1.6 增加字段及索引

命令rails g migration AddMobileToUsers mobile:string:index
注:index 和字段间使用冒号:隔开

class AddMobileToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :mobile, :string
    add_index :users, :mobile
  end
end

2.1.7 删除字段

命令rails g migration RemoveEmailFromUsers email:string
创建迁移文件 :20200829072010_remove_email_from_users.rb

class RemoveEmailFromUsers < ActiveRecord::Migration[6.0]
  def change
    remove_column :users, :email, :string
  end
end

2.1.8 修改字段

  • 修改字段类型
  def change
    change_column :users, :email, :text
  end

上面的代码把 users 数据表的 email 字段修改为 :text 字段。
注:change_column 命令是无法撤销的

  • 设置字段可以为空或不可以为空
change_column_null :products, :name, false
  • 修改字段的默认值
change_column_default :products, :approved, from: true, to: false

change_column_default :products, :approved, false

第二种写法没法撤销

2.1.9 增加外键

add_foreign_key :articles, :authors

上面的代码为 articles 数据表的 author_id 字段添加外键,这个外键会引用 authors 数据表的 id 字段。

2.1.10 删除外键

# 让 Active Record 找出列名
remove_foreign_key :accounts, :branches
 
# 删除特定列上的外键
remove_foreign_key :accounts, column: :owner_id
 
# 通过名称删除外键
remove_foreign_key :accounts, name: :special_fk_name

2.2 模型生成器

模型和脚手架生成器会生成适用于添加新模型的迁移.会在生成模型的同时生成数据表
rails generate model form field:string title:string
在这里插入图片描述

2.3 传递修饰符

字段修饰符可以在创建或修改字段时使用
rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}

class AddDetailsToProducts < ActiveRecord::Migration[6.0]
  def change
    add_column :products, :price, :decimal, precision: 5, scale: 2
    add_reference :products, :supplier, polymorphic: true, null: false
  end
end

3 运行迁移

3.1 回滚

  • 回滚最后一个迁移
    rails db:rollback
  • 要想取消多个迁移,可以使用 STEP 参数:
    rails db:rollback STEP=3
  • db:migrate:redo 任务用于回滚最后一个迁移并再次运行这个迁移,可以使用 STEP 参数
    rails db:migrate:redo STEP=3

3.2 安装数据库

rails db:setup
rails db:setup 任务用于创建数据库,加载数据库模式,并使用种子数据初始化数据库。

3.3 重置数据库

rails db:reset任务用于删除并重新创建数据库,其功能相当于 rails db:drop db:setup。

3.4 运行指定迁移

使用 db:migrate:up 和 db:migrate:down 任务
只需指定版本,对应迁移就会调用它的 change 、up 或 down 方法
rails db:migrate:up VERSION=20080906120000
上面的命令会运行 20080906120000 这个迁移,调用它的 change 或 up 方法。db:migrate:up 任务会检查指定迁移是否已经运行过,如果已经运行过就不会执行任何操作。

3.5 在不同环境中运行迁移

rails db:migrate RAILS_ENV=test 在测试环境中运行迁移
bin/rails db:migrate 任务默认在开发环境中运行迁移。要想在其他环境中运行迁移,可以在执行任务时使用 RAILS_ENV 环境变量说明所需环境。

4 迁移和种子数据

  • 使用 Rails 内置的“种子”特性可以快速简便地完成创建数据库后添加初始数据的任务。
  • 用 Ruby 代码填充 db/seeds.rb 文件,然后执行 rails db:seed
5.times do |i|
  Product.create(name: "Product ##{i}", description: "A product.")
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值