Setting different default values in rails migrations?

喜夏-厌秋 提交于 2019-12-11 11:39:47

问题


I'm trying to write a migration and it looks something like this:

class AddStatusToWorks < ActiveRecord::Migration
  def self.up
    change_table :works do |t|
        t.string :status
    end
  end

  def self.down
    change_table :works do |t|
        t.remove :status
    end
  end
end

Thing is, I want to set different default values for "status" based on a boolean value that's already in the table, "complete." If complete = true, status = "complete." If not, status = "work in progress." (The reason I want a string instead of keeping complete as the boolean is because I want there to be able to be more than two possibilites for status.) Any idea how to do that? Do I just stick an if statement in there like this

change_table :works do |t|
        t.string :status
           if (:complete == true)
               :value => "complete"
           else
               :value => "wip"
end

Er, so that doesn't look quite right. I googled a bit and found that you can set :default values, but that's not quite what I'm going for. Any ideas/help would be lovely. Thanks!


回答1:


You don't need a default at all, you just need to add the new column and give it values. Something like this should work:

def self.up
  change_table :works do |t|
      t.string :status
  end
  Works.reset_column_information
  Works.where(:complete => true).update_all(:status => 'complete')
  Works.where(:complete => [false, nil]).update_all(:status => 'wip')
end

See the Migrations Guide for information on reset_column_information.

You could also do it straight in the database but you have to be careful about different boolean representations (PostgreSQL wants 't' and 'f', MySQL wants 1 and 0, SQLite wants 1 and 0 but Rails mistakenly uses 't' and 'f', ...):

t = connection.quote(true)
connection.execute(%Q{
  update works
  set status = case complete
    when #{t} then 'complete'
    else 'wip'
  end
})



回答2:


Remember that default values are created immediately when the record is created, and thus don't yet have values for fields w/o defaults. You'll likely want to move this sort of logic to your model. Perhaps in an ActiveRecord callback, i.e. before_validation or before_save.



来源:https://stackoverflow.com/questions/12612969/setting-different-default-values-in-rails-migrations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!