How to create a table in rails?

1 minute read

Table

Create an articles table

$ bin/rails generate migration CreateArticles

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|

      t.timestamps
    end
  end
end

Table with fields

Create an articles table with title and content fields

$ bin/rails generate migration CreateArticles title content:text

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :content

      t.timestamps
    end
  end
end

Table with references

Create an articles table with references

$ bin/rails generate migration CreateArticles title content:text user:references

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :content
      t.references :user, null: false, foreign_key: true

      t.timestamps
    end
  end
end

Table with polymorphic associations

Create an articles table with polymorphic associations

bin/rails generate migration CreateArticles title content:text resource:references{polymorphic}

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :content
      t.references :resource, polymorphic: true, null: false

      t.timestamps
    end
  end
end

Table with index

Create an articles table with index

bin/rails generate migration CreateArticles title content:text slug:index

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :content
      t.string :slug

      t.timestamps
    end
    add_index :articles, :slug
  end
end

Table with uniq index

Create an articles table with uniq index

bin/rails generate migration CreateArticles title content:text slug:uniq

Generates the following migration:

# db/migrate/20230803041631_create_articles.rb
class CreateArticles < ActiveRecord::Migration[7.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :content
      t.string :slug

      t.timestamps
    end
    add_index :articles, :slug, unique: true
  end
end

References

Note

All the commands have been tested with rails 7.1 and the result may differ with prior versions