It looks like "default: 0" does what you want:
class CreateAnothers < ActiveRecord::Migration def change create_table :anothers do |t| t.date :start, null: false, default: 0 t.timestamps null: false end end end 😉 ➤ rake db:migrate == 20150813201736 CreateAnothers: migrating =================================== -- create_table(:anothers) -> 0.0943s == 20150813201736 CreateAnothers: migrated (0.0944s) ========================== [1] pry(main)> Another.create (0.2ms) BEGIN SQL (0.5ms) INSERT INTO `anothers` (`created_at`, `updated_at`) VALUES ('2015-08-13 20:19:02', '2015-08-13 20:19:02') (34.6ms) COMMIT =>
After clarifying the requirements
So in other words, what is your goal? Do you want to run the update through the rails to change the table? If so, you can do
ActiveRecord::Base.connection.execute("UPDATE table SET field='0000-00-00' WHERE id=
Is this allowed? (YES)
Update
Well, if you want it to be pure Rails, let it be like this:
[5] pry(main)> a.update_attribute(:start, nil) (1.5ms) BEGIN SQL (3.6ms) UPDATE `anothers` SET `start` = NULL, `updated_at` = '2015-08-14 16:31:22' WHERE `anothers`.`id` = 1 (36.8ms) COMMIT => true [6] pry(main)> a.update_attribute(:start, "0000-00-00") (0.2ms) BEGIN (0.1ms) COMMIT => true mysql> select * from anothers; +----+-------+---------------------+---------------------+ | id | start | created_at | updated_at | +----+-------+---------------------+---------------------+ | 1 | NULL | 2015-08-14 16:30:39 | 2015-08-14 16:31:22 | +----+-------+---------------------+---------------------+ 1 row in set (0.00 sec)
As you can see, update_attribute does not work, but
[8] pry(main)> a.update_column(:start, "0000-00-00") SQL (47.1ms) UPDATE `anothers` SET `anothers`.`start` = '0000-00-00' WHERE `anothers`.`id` = 1 => true mysql> select * from anothers; +----+------------+---------------------+---------------------+ | id | start | created_at | updated_at | +----+------------+---------------------+---------------------+ | 1 | 0000-00-00 | 2015-08-14 16:30:39 | 2015-08-14 16:31:22 | +----+------------+---------------------+---------------------+ 1 row in set (0.00 sec)
update_column does!
Please note that after you do a.update_column(:start, "0000-00-00") , the date field in your variable (in my case "a.start") will be set to "0000-00-00 " And if you want it to display the actual nil value, you need to reload it, like a.reload .
user4776684
source share