The default value is not populated when migrating using Rails and Postgresql

I am currently trying to perform this migration:

class AddDroppedProjectsCountToUser < ActiveRecord::Migration def self.up add_column :users, :dropped_projects, :integer, {:default=>0, :required=>true} end def self.down remove_column :users, :dropped_projects end end 

The column was added correctly, but none of the old entries are filled with 0. They are zero. I tried using default=>'0' , but to no avail. Any idea why this might happen? (Rails 3.0.3)


Edited to add: when I create a new user, it works fine, and everything looks right. These are just old users who still have zero for this value in the table.

+6
sql ruby-on-rails postgresql ruby-on-rails-3
source share
3 answers

What happens if you say:

 def self.up add_column :users, :dropped_projects, :integer, :null => false, :default => 0 end 

instead of this? Without :null=>false you still allow NULL in dropped_projects , so there is no reason for PostgreSQL to make them 0. In addition, I do not think that :required is a valid parameter for add_column ; since the parameters are just plain Hash , and add_column is just the parameters he knows about, your stray :required option is ignored.

+12
source share

You can do it:

(taken from http://apidock.com/rails/ActiveRecord/Migration )

Using the model after changing its table

Sometimes you need to add a column to a hyphen and fill it in immediately after. In this case, you need to call Base # reset_column_information to ensure that the model has the latest column data after adding a new column. Example:

 class AddPeopleSalary < ActiveRecord::Migration def up add_column :people, :salary, :integer Person.reset_column_information Person.all.each do |p| p.update_column :salary, SalaryCalculator.compute(p) end end end 
+3
source share

I believe that this is due to the fact that you are changing the old migration, and not creating a new one. In this case, the solution should check the schema file ( schema.rb ). It does not change automatically and adds

 t.integer "dropped_projects", default: 0, null: false 
0
source share

All Articles