create table if not exist rails

class CreateYourTableName < ActiveRecord::Migration[6.0]
  def change
    create_table :your_table_name do |t|
      t.string :column_name
      t.integer :another_column
      t.timestamps
    end unless table_exists?(:your_table_name)
  end
end

Explanation:

  1. class CreateYourTableName < ActiveRecord::Migration[6.0]: Defines a migration class named CreateYourTableName, where YourTableName should be replaced with the actual name you want for your table. This class inherits from ActiveRecord::Migration[6.0], indicating it's a migration for Rails version 6.0.

  2. def change: Begins the migration's change method, used to define the changes to be applied to the database.

  3. create_table :your_table_name do |t|: Starts creating a table named your_table_name within the database. Replace your_table_name with your desired table name. The block |t| is used to define table columns.

  4. t.string :column_name: Adds a column named column_name to the table, where string specifies the data type of the column. Replace column_name with the desired column name and adjust the data type as needed (e.g., integer, text, boolean, etc.).

  5. t.integer :another_column: Adds another column named another_column with the data type integer. Adjust the column name and data type as required.

  6. t.timestamps: Automatically adds created_at and updated_at columns to track timestamps for when records are created and updated.

  7. end unless table_exists?(:your_table_name): This line ensures that the table is only created if it doesn't already exist in the database. It checks whether the table exists using the table_exists? method before executing the create_table block.

Note: Ensure to replace YourTableName, your_table_name, column_name, and another_column with your preferred names and configurations for the table and columns. ```