28
loading...
This website collects cookies to deliver better user experience
NULL
values in your table columns. Sometimes you might want to specify that a certain value has to exist, and you can apply a null constraint to enforce that. NULL
value, the database transaction will roll back nicely and prevent it from doing so.add_column
helper, you can add the null
keyword argument to specify if the new column allows NULL
values or not. You have the option to add the default
keyword argument too if you need to define what the default value of this column should be. This will ensure that new records have a value even if you don't specify one, so they can abide by your null constraint.add_column :articles, :published, :boolean, null: false, default: false
boolean
column called published
to the articles
table. The null: false
parameter means this column does not allow NULL
values. The default: false
tells us this column will default to false whenever a value isn't specified.create_table
helper to define our table and columns.null: false
keyword argument to any column in your create_table
call. You can also add the default:
in the same way to define a default value on a column.create_table "articles", force: true do |t|
t.string "name", null: false
t.text "body"
t.boolean "published", default: false
end
NULL
values.NULL
value with a not null value in order to apply that constraint.change_column_null
helper to update the null constraint on an existing column. It takes a few arguments and should look something like this:def change
change_column_null(:articles, :name, false, "Untitled")
end
:articles
:name
NULL
, what do we replace NULL
values with?change
method, Active Record will try its best to roll back the migration just by doing the opposite. In other words, it knows when you call add_column
to pretty much call remove_column
on the roll back. The same is true for the change_column_null
method.change
method though. One example is if you need to do a data migration or backfill some data of some kind too.rake db:migrate
or rake db:migrate:rollback
, under the hood your migration is either running the up
or down
case.rake db:migrate:status
to see which migrations are currently up or down (in other words which have run or not).up
and down
methods instead of jamming everything into the change
method and relying on magic.up
and down
methods:def up
add_column :articles, :published, :boolean
rename_column :articles, :featured, :temporary_featured
end
def down
rename_column :articles, :temporary_featured, :featured
remove_column :articles, :published
end
down
method. We have more control over what happens.change
is good enough!