'Rails migration, how to change the table column
I know that usually when we want to change one column of a table in the rails database. But now I want to make a big change to my projects table and sample table. What is the best way to achieve this? originally
projects table:
class CreateProjects < ActiveRecord::Migration[6.0]
def change
create_table :projects do |t|
t.string :name
t.string :project_id1
t.string :project_id2
t.text :curated_description
t.integer :num_of_samples
t.integer :num_of_runs
t.integer :population
t.text :related_publications
t.text :original_description
t.timestamps
end
end
end
Sample table:
class CreateSamples < ActiveRecord::Migration[6.0]
def change
create_table :samples do |t|
t.string :sample_name
t.string :project_name
t.string :run_id
t.string :second_run_id
t.string :meta_project_id
t.string :experiment_type
t.string :nr_reads_sequenced
t.string :instrument_model
t.string :disease_phenotype
t.string :is_disease_stage_available
t.string :disease_stage
t.text :more
t.text :more_info
t.string :country
t.string :collection_date
t.string :sex
t.integer :host_age
t.string :diet
t.string :longitude
t.string :lattitude
t.float :BMI
t.string :associated_phenotype
t.string :QC_status
t.text :recent_antibiotics_use
t.text :antibiotics_used
t.text :antibiotics_dose
t.integer :days_without_antibiotics_use
t.text :original_description
t.text :curated_description
t.references :project, null: false, foreign_key: true
t.timestamps
end
end
end
And these two migration files are the earliest two files in my migrations files. At first, I want to drop these two files (also there is one join table related these two tables and I drop it as well), and I have already run the database migration to drop them. But when I want to create a new migration file using
rails generate migration createProjects
it tells me that there is a conflict because we have already have a file named xxx_creat_projects, and I do know that it is the earliest one I create, but I have already create the migration to drop the old tables, now how can I create a new projects and samples table. Or it is better if someone can tell me how to achieve this (make a big change to these tables because I must change a lot of columns). Thanks!
Solution 1:[1]
0
First, you need to create a migration file by running the command:
rails generate migration YourMigrationName
And then edit the migration file and add change method definition like this:
def change
change_column :table_name, :column_name, :new_type
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
