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:
class CreateYourTableName < ActiveRecord::Migration[6.0]
: Defines a migration class namedCreateYourTableName
, whereYourTableName
should be replaced with the actual name you want for your table. This class inherits fromActiveRecord::Migration[6.0]
, indicating it's a migration for Rails version 6.0.def change
: Begins the migration'schange
method, used to define the changes to be applied to the database.create_table :your_table_name do |t|
: Starts creating a table namedyour_table_name
within the database. Replaceyour_table_name
with your desired table name. The block|t|
is used to define table columns.t.string :column_name
: Adds a column namedcolumn_name
to the table, wherestring
specifies the data type of the column. Replacecolumn_name
with the desired column name and adjust the data type as needed (e.g.,integer
,text
,boolean
, etc.).t.integer :another_column
: Adds another column namedanother_column
with the data typeinteger
. Adjust the column name and data type as required.t.timestamps
: Automatically addscreated_at
andupdated_at
columns to track timestamps for when records are created and updated.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 thetable_exists?
method before executing thecreate_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.
```