0

Recently I realized that none of my database columns have default values. If an object is instantiated and then saved, it might have nil values for any fields that aren't filled out.

I can make it so that I explicitly initialize these values, but then I've got some places where two controllers are creating the same object, but I didn't think of moving that code into a separate module.

I can also choose to update my migrations to specify default values, which seems cleaner.

I've decided to go with migrations. It is not a good idea to edit old migrations, so I'm creating a new migration and specifying that I want to change certain columns.

Looking at how I should change columns, I have determined that I will use this

def change
  change_column :products, :size, :default => 0
end

Will this modify existing records that currently have nil set for those records?

1 Answer 1

2

No, it will not update your old records.

You should NEVER change old migrations, it is a relief you noticed that.

I suggest you to create a rake task that will update all the fields OR you can do it directly on console like the code below.

Product.update_all({ size: 0 }, { size: nil })
Sign up to request clarification or add additional context in comments.

3 Comments

Why is it bad practice to change old migrations? If you do, couldn't you simply db:drop and db:create, if needed?
Imagine you have created the migrations and executed on production, or if someone else that is working on the same project with you got your migrations and executed, and after that you change old migrations. It will create some issues.
Adding it here because I can never find it. If you want to execute a method for every product use find_each: Product.find_each{ |p| p.do_something! }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.