开发者

Default value not populating in migration with Rails and Postgresql

I am currently trying to run 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 is added correctly, but none of the old records are populated with 0. They are nil. I have tried using default=>'0' as well, to no avail. Any idea why this mig开发者_JS百科ht be happening? (Rails 3.0.3)


Edited to add: When I create a new user it works fine, and everything looks correct. It's just the old users that still have nil for that value in the table.


What happens if you say:

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

instead? Without the :null=>false you're still allowing NULL in dropped_projects so there's no reason for PostgreSQL to make them 0. Also, I don't think :required is a valid option for add_column; since the options are just a simple Hash and add_column only looks for options it knows about, your stray :required option is silently ignored.


you could do this:

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

Using a model after changing its table

Sometimes you’ll want to add a column in a migration and populate it immediately after. In that case, you’ll need to make a call to Base#reset_column_information in order to ensure that the model has the latest column data from after the new column was added. 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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜