3

I've set up a new migration file:

class ChangeCourseDefaults < ActiveRecord::Migration
  def self.up
    change_column_null :course_objects, :active, false
    change_column_default :course_objects, :active, 0
  end
end

I run it this way on my debian server (rails 4.2.1 ruby 2.1)

sudo bundle exec rake db:migrate:up VERSION=20150720095700 RAILS_ENV=test

Then I got this error:

Mysql2::Error: Data truncated for column 'active' at row 1: ALTER TABLE `course_objects` CHANGE `active` `active` tinyint(1) NOT NULL/var/www/html/test/xyz/vendor/bundle/ruby/2.1.0/gems/activerecord-4..2.1/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:299:in `query'

Whats the problem?

3
  • is there any record previously which is already null.? please check Commented Jul 20, 2015 at 8:50
  • yes there are numberous ones Commented Jul 20, 2015 at 8:56
  • yes that is why when this line change_column_null :course_objects, :active, false runs it will check for all values and confirm there should not be any null. and here it crashes. but i guess the answer pasted below will solve your problem. Commented Jul 20, 2015 at 8:58

2 Answers 2

9

You can use change_column_null

class ChangeCourseDefaults < ActiveRecord::Migration
  def change
    change_column_null :table_name, :column_name, false, 0 # set default as 0
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

I got this error: undefined method null' for #<ChangeCourseDefaultsNull:0x00000005be8de0>/var/www/html/test/xyz/vendor/bundle/ruby/2.1.0/gems/activerecord-4.2.1/lib/active_record/migration.rb:661:in block in method_missing'
replace null with false.
The docs for change_column_null say: "The method accepts an optional fourth argument to replace existing +NULL+s with some other value. Use that one when enabling the constraint if needed, since otherwise those rows would not be valid. Please note the fourth argument does not set a column’s default."
2
class ChangeCourseDefaults < ActiveRecord::Migration
  def change
    change_column_null :course_objects, :active, false, 0
  end
end

reference: change_column_null for existing column

1 Comment

i just added the answer because above has few issues. please accept above answer Felix once it is correct. he has more right.:)

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.