Łukasz Korol Łukasz Korol - 5 months ago 8
Ruby Question

Issue with adding a not null columns to an existing table

I have problem with adding not nullable columns to a table.
I read many posts about this and it should be correct.

Migration code:

def change
add_column :individual_trainings, :start_on, :time
add_column :individual_trainings, :end_on, :time

change_column_null :individual_trainings, :start_on, false
change_column_null :individual_trainings, :end_on, false


PG::NotNullViolation: ERROR: column "start_on" contains null values...

I don't have any idea why isn't working. How should I correct write change method?

Thanks in advance.

It was my big fault. I was have one record in this table... I cleared table and migrate. Now it's working. Sorry for my stupidity and waste of your time.


try this,

 def change
   change_column_default :individual_trainings, :start_on, Time.now
   change_column_default :individual_trainings, :end_on, Time.now

For More details see http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column_default

And To set not null contraint do this

def change
  change_column :individual_trainings, :start_on, :time, :null => false
  change_column :individual_trainings, :end_on, :time, :null => false