Read the Rails Guide (Active Record Migration) again

1. What is Active Record migration?

--Some of the features of Active Record. --It makes it easy to create and modify tables.

2. Migration overview

--Each migration is considered a new version of the database. --Active Record is managed in chronological order, so you can update to the latest version of the schema from any point in the past. --Active Record updates the db / schema.rb file to match the latest structure of the database. --Migration has the image of "defining the action you want to perform as you move forward in time." --There is no table before performing the migration. Performing a migration creates a table, and rolling back the migration deletes the table.

3. Create a migration

--The created migration is saved in the db / migrate directory. --The migration file name will be in a format like YYYYMMDDHHMMSS_create_products.rb, and the date and time will identify the migration. The migration name is described after the underscore. --The name of the migration class must match the second half of the file name.
(Example) In 20080906120001_add_details_to_products.rb, a class called ʻAddDetailsToProducts` needs to be defined. --In Rails, the execution order of migration is determined by the time stamp of the file name. Therefore, when copying a migration from another application or creating it yourself, you need to be careful about the execution order.

3-1. Migration when adding / deleting columns

--When adding a column
Generate by adding ʻadd_columnin the format of" AddColumnToTable ". <br> --When deleting a column <br> Generate by addingremove_column` in the format of" RemoveColumnFromTable ".

Example: When adding an email column to the Users table
$ rails g migration AddEmailToUsers email:string

Example: When removing a hobby column from the Users table
$ rails g migration RemoveHobbyFromUsers hobby:string

When the above migration generation command is executed, the following migration file is generated.

When adding a column


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

When deleting a column


class RemoveHobbyFromUsers < ActiveRecord::Migration[5.0]
  def change
    remove_column :users, :hobby, :string
  end
end

3-2. Migration when generating a table

--Specify the column you want to add in the "CreateTable" format.

$ rails g migration CreatePosts name:string content:text

Doing the above will generate:

When creating a table


class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.string :name
      t.text :content

      t.timestamps
    end
  end
end

The content generated so far is just a starting point, You can generate db / migrate / YYYYMMDDHHMMSS_add_genre_to_posts.rb and add / delete columns to the table.

3. Specify references

You can specify references as the column type.

$ rails g migration AddUserRefToPosts user:references

Running the above will generate:

class AddUserRefToPosts < ActiveRecord::Migration[5.0]
  def change
    add_reference :posts, :user, foreign_key: true
  end
end

Performing this migration will create a ʻuser_id` in the posts table and add the appropriate index.

3-4. Generate join tables (join tables)

Migration to generate a join table is also possible if "JoinTable" is part of the name.

$ rails g migration CreateJoinTableUserPost user post

Running the above will generate:

class CreateJoinTableUserPost < ActiveRecord::Migration[5.0]
  def change
    create_join_table :users, :posts do |t|
      # t.index [:user_id, :post_id]
      # t.index [:post_id, :user_id]
    end
  end
end

4-Supplement. About join tables (join tables)

Generate a join table when using. The join table stores ʻid: keys such as primary key and foreign key`.

#app/models/user.rb
class User < ActiveRecord::Base
   has_and_belongs_to_many :posts
end

#app/models/post.rb
class Post < ActiveRecord::Base
   has_and_belongs_to_many :users
end

@user.posts #-> all posts from join table
@post.users #-> all users from join table

That is, if you need to associate has_many <-> has_many, you need a join table to store all references to relative foreign keys.

3-5. Generate a model

In migration when generating a new model, if you specify the required columns, those additional columns will be generated at the same time.

Generate User model


$ rails g model User name:string description:text

Running the above will generate:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

3-6. Pass the modifier

[Column modifier](https://railsguides.jp/active_record_migrations.html#%E3%82%AB%E3%83%A9%E3%83%A0%E4%BF%AE%E9%A3%BE%E5 You can also pass% AD% 90) directly on the command line. Field types (data type, association type) can be added from the back using curly braces {}.

$ rails g migration AddDetailsToProducts 'price:decimal{5,2}' supplier:references{polymorphic}

This will generate a migration similar to the following:

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

4. Make your own migration

4-1. Create a table

The create_table method is the most basic method and is used when creating a model.

create_table :posts do |t|
  t.string :name
end

The above creates a posts table and creates a column called name in it. If you don't want to use the primary key, you can specify the ʻid: false` option, and if you want the options used by a particular database, you can write the SQL fragment as follows after the: options option.

create_table :products, options: "ENGINE=BLACKHOLE" do |t|
  t.string :name, null: false
end

In the above migration, ENGINE = BLACKHOLE is specified in the SQL statement that generates the table.

You can also use the : comment option to write a description of the table and save it in the database itself. It makes it easier for large applications to understand the data model and also generates documentation, so it is recommended to add such comments to the migration.

4-2. Create a table join

The migration's create_join_table method creates a has_and_belongs_to_many (HABTM) table join.

create_join_table :posts, :categories

The above creates the categories_products table, in which the category_id and post_id columns are created. These columns have a: null option, which defaults to false. You can override the default value by specifying the : column_options option.

create_join_table :posts, :categories, column_options: { null: true }

If you want to use your own table name, you can specify it with: table_name.

create_join_table :posts, :categories, table_name: :categorization

The categorization table is created by doing the above.

create_join_table can also take a block as an argument. This is used to add indexes and columns.

create_join_table :posts, :categories do |t|
  t.index :post_id
  t.index :category_id
end

4-3. Change the table

Modify an existing tablechange_tableThe method iscreate_tableIt is very similar to and can be used in the same way. Yield to the block (of the block|t|The object (which replaces) can be used in the following writing style.

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

The migration above removes the description and name columns, creates a string column part_number, adds an index to it, and finally renames the ʻupccode` column.

4-4. Change the column

For migration, you can use the change_column method in addition to the remove_column and ʻadd_column`.

change_column :products, :part_number, :text

Recommended Posts

Read the Rails Guide (Active Record Migration) again
Read the Rails Guide (Overview of Action Controller) again
[Rails] Delete the migration file
What is Rails Active Record?
Check the migration status of rails
Rails migration
[Ruby on Rails] About Active Record callbacks
[Rails] Active Record method that even beginners often use
I read the "Object-Oriented Practical Guide", so a memorandum