Zack Shapiro
Zack Shapiro

Reputation: 6998

Writing a database migration that turns datetime null:false to true

I'm trying to write a database migration that changes the datetime fields in my join table from null to true but something isn't working correctly. Here's my code:

class ChangeDateColumnsInCirclesUsers < ActiveRecord::Migration
  def change
    change_column :circles_users, :created_at, :datetime, :null => true
    change_column :circles_users, :updated_at, :datetime, :null => true
  end
end

This isn't working. Any ideas on how to have those null values be set to true instead of false?

Upvotes: 0

Views: 781

Answers (2)

felipeclopes
felipeclopes

Reputation: 4070

What are you trying to accomplish with this?

A datetime columns can't have its default value to true.

Read the spec: Migrations


Rails does not support dynamic default values in migration script. SO if you want the current time you can easily add them at the model level.

1) Setting default values using after_initialize callback

class Test
  def after_initialize
    self.day ||= Date.today if new_record?
  end
end

t = Test.new
t.day # will return today's date
t.save
t.day # will return today's date

Edit:

In the comments we figured out that you don't want to worry filling the updated_at and created_at the thing is that ActiveRecord already do it for you.

So you don't have to remove nor change these columns.

"The timestamp columns created_at and updated_at which Active Record populates automatically will also be added." from Migrations

Hope it helps!

Upvotes: 0

Dipak Panchal
Dipak Panchal

Reputation: 6036

try this

change_column :table_name, :created_at, :datetime, :null => true, :default => nil

and run migration

Upvotes: 1

Related Questions