Reputation: 139
I’ve started learning Ruby on Rails recently. I did a blogger tutorial. I want to add one more field archive to my database, but not sure is it possible just to write manually and which command to call? Here is my database where I want to add code:
class CreateArticles < ActiveRecord::Migration[6.1]
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
end
end
And I want to add a new field archive which is boolean and by default false? Also is it okay to add in this schema new field or is it better in some other?
Upvotes: 0
Views: 621
Reputation: 31
1.Run the migration from command line to add the new column
$ rails g migration add_column_archive_to_articles archive:boolean
The above command will create a new migration file in your db/migrate
folder.
2.As of now there's no option to add default value to a column, which can be defined through terminal. Set the new column value to true/false
by editing the new migration file created. Your migration file will look like this.
class AddColumnArchiveToArticles < ActiveRecord::Migration
def change
add_column :articles, :archive, :boolean, default: false
end
end
3.Then do
$ rails db:migrate
Upvotes: 3
Reputation: 6354
Migrations should never be changed afterwords. That is why they are migrations, and not a static schema definitions.
Just generate a new migration using rails g migration AddArchiveToArticles
and then check the rails documentation for add_column
to see how you can alter a table to add a column. It also supports default values :)
Upvotes: 1