4. ROR: Database and Migrations

1、 Common Concept

Database Table
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png

2 Create a Database

image.png

2.1 Create a new user to use the database

image.png
image.png

3 Migrations

image.png
image.png
  • 使用应用程序代码保存数据库模式
  • 可执行的和可重复的
  • 允许共享模式更改

4 Generate Migrations

image.png

语法形式

rails generate migration MigrationName

名称有时间,和下划线组成(自动转换)


image.png
image.png

新增method在db对应的migration中

class DonothingYet < ActiveRecord::Migration[5.2]
  def change
  end
  def up    
  end
  def down
  end
end
通过model 创建migration,名称符合驼峰式命名规则
image.png

Example

rails generate model User
Running via Spring preloader in process 4414
      invoke  active_record
      create    db/migrate/20190507022013_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
  • 注:model name is going to be singular,the table name is going to be plural,
image.png
image.png

class CreateUsers < ActiveRecord::Migration[5.2]
# db/migrate/20190507022013_create_users.rb
  def up
    # create_table :users, :id=>false do |t|
    create_table :users do |t|

      t.column "first_name", :string , :limit => 20# long format
      t.string "last_name", :limit => 10 #short format
      t.string "email", :default => '', :null => false
      t.string "password", :limit => 40

      t.timestamps
      # t.datetime "create_at"
      # t.string "datetime_at"
    end
  end

  def down
    drop_table :users
  end
end

Running Migrations

rails db:migrate

== 20190507022013 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0695s
== 20190507022013 CreateUsers: migrated (0.0696s) =============================


>mysql -u rails_user -p simple_cms_development
mysql> SHOW TABLES;
+----------------------------------+
| Tables_in_simple_cms_development |
+----------------------------------+
| ar_internal_metadata             |
| schema_migrations                |
| users                                      |
+----------------------------------+

mysql> SHOW FIELDS FROM users;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id                | bigint(20)     | NO   | PRI | NULL    | auto_increment |
| first_name | varchar(20)  | YES  |     | NULL    |                |
| last_name  | varchar(10)  | YES  |     | NULL    |                |
| email          | varchar(255) | NO   |     |         |                |
| password   | varchar(40)  | YES  |     | NULL    |                |
| created_at | datetime      | NO   |     | NULL    |                |
| updated_at | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

mysql> SHOW FIELDS FROM schema_migrations;
+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| version | varchar(255) | NO   | PRI | NULL    |       |
+---------+--------------+------+-----+---------+-------+

mysql> SELECT * FROM schema_migrations;
+----------------+
| version        |
+----------------+
| 20190506075014 |
| 20190507022013 |
+----------------+

db schema update same time

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_05_07_022013) do

  create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
    t.string "first_name", limit: 20
    t.string "last_name", limit: 10
    t.string "email", default: "", null: false
    t.string "password", limit: 40
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

rails db:migrate VERSION=0
== 20190507022013 CreateUsers: reverting ======================================
-- drop_table(:users)
   -> 0.1590s
== 20190507022013 CreateUsers: reverted (0.1591s) =============================

== 20190506075014 DonothingYet: reverting =====================================
== 20190506075014 DonothingYet: reverted (0.0000s) ============================

$ rails db:migrate:status

database: simple_cms_development
 Status   Migration ID    Migration Name
--------------------------------------------------
  down    20190506075014  Donothing yet
  down    20190507022013  Create users

$ rails db:migrate VERSION=20190506075014
== 20190506075014 DonothingYet: migrating =====================================
== 20190506075014 DonothingYet: migrated (0.0000s) ============================

rails db:migrate:status

database: simple_cms_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20190506075014  Donothing yet
  down    20190507022013  Create users


maxiaoan:~/simple_cms$ rails db:migrate
== 20190507022013 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.1286s
== 20190507022013 CreateUsers: migrated (0.1287s) =============================

maxiaoan:~/simple_cms$ rails db:migrate:status

database: simple_cms_development

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20190506075014  Donothing yet
   up     20190507022013  Create users

image.png

Migrations Methods

image.png

image.png

image.png

image.png

Examples of migration methods

rails generate migration AlterUsers
class AlterUsers < ActiveRecord::Migration[5.2]
  def up
    rename_table("users", "admin_users")
    add_column("admin_users", "username", :string,:limit =>25, :after => "email")
    change_column("admin_users", "email", :string, :limit =>100)
    rename_column("admin_users", "password", "hashed_password")
    puts "*** Add index ***"
    add_index("admin_users", "username")
  end

  def down
    remove_index("admin_users", "username")
    rename_column("admin_users", "hashed_password", "password")
    change_column("admin_users", "email", :string, :default => '', :null =>false)
    remove_column("admin_users", "username")
    rename_table("admin_users", "users")
  end
end

~/simple_cms$ rails db:migrate
== 20190507043136 AlterUsers: migrating =======================================
-- rename_table("users", "admin_users")
   -> 0.0481s
-- add_column("admin_users", "username", :string, {:limit=>25, :after=>"email"})
   -> 0.0569s
-- change_column("admin_users", "email", :string, {:limit=>100})
   -> 0.0271s
-- rename_column("admin_users", "password", "hashed_password")
   -> 0.0089s
*** Add index ***
-- add_index("admin_users", "username")
   -> 0.0222s
== 20190507043136 AlterUsers: migrated (0.1637s) ==============================

$ rails db:migrate VERSION=0

$ rails db:migrate:status
database: simple_cms_development

 Status   Migration ID    Migration Name
--------------------------------------------------
  down    20190506075014  Donothing yet
  down    20190507022013  Create users
  down    20190507043136  Alter users

$ rails db:migrate:status
maxiaoan:~/simple_cms$ rails generate model Subject
Running via Spring preloader in process 7693
      invoke  active_record
      create    db/migrate/20190507061832_create_subjects.rb
      create    app/models/subject.rb
      invoke    test_unit
      create      test/models/subject_test.rb
      create      test/fixtures/subjects.yml
maxiaoan:~/simple_cms$ rails generate model Page
Running via Spring preloader in process 7706
      invoke  active_record
      create    db/migrate/20190507061838_create_pages.rb
      create    app/models/page.rb
      invoke    test_unit
      create      test/models/page_test.rb
      create      test/fixtures/pages.yml
maxiaoan:~/simple_cms$ rails generate model Section
Running via Spring preloader in process 7719
      invoke  active_record
      create    db/migrate/20190507061850_create_sections.rb
      create    app/models/section.rb
      invoke    test_unit
      create      test/models/section_test.rb
      create      test/fixtures/sections.yml

Subjects表的字段

class CreateSubjects < ActiveRecord::Migration[5.2]
  def up
    create_table :subjects do |t|
        t.string "name"
        t.integer "position"
        t.boolean "visible", :default => false
      t.timestamps
    end

   def down
        drop_table :subjects
    end
  end
end

Pages 表的字段

class CreatePages < ActiveRecord::Migration[5.2]
  def up
    create_table :pages do |t|
        t.integer "subject_id"
        t.string "name"
        t.string "permalink"
        t.integer "position"
        t.boolean "visible", :default => false
        t.timestamps
    end
    add_index("pages", "subject_id")
    add_index("pages", "permalink")
  end

 # don't need to drop indexes when dropping the whole tables
  def down 
    drop_table :pages
  end

end

sections 表的字段

class CreateSections < ActiveRecord::Migration[5.2]
  def up
    create_table :sections do |t|
        t.integer "page_id"
        t.string "name"
        t.integer "position"
        t.boolean "visible", :default => false
        t.string "content_type"
        t.text "content"
        t.timestamps
    end
    add_index("sections", "page_id")
  end

  def down
    drop_table :sections
  end
end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。