• 在Migration中操作新添加的字段


    在Migration中操作新添加的字段

    在有些情况下,我们需要在某个migration中对新增加的字段进行操作,比如下面这个将name改成first_name和last_name的migration:


    def self.up
      add_column :profiles, :last_name, :string
      add_column :profiles, :first_name, :string
      Profile.find(:all).each do |profile|
        profile.first_name = profile.name
        profile.save(false)
      end
      remove_column :profiles, :name
    end

    这段代码看起来没什么问题,但是如果你真的这么做,那就惨了,你数据库中所有用户的名字信息都会丢失,而不会如你所愿的保存到first_name中,这是因为,当你为profiles表添加first_name字段时,Profile model已经完成了初始化,因此在它的columns里面是不存在first_name的,自己它也就不会被保存到数据库中,因此,要使上面这段代码工作正常,你需要在修改数据库后重新加载Profile model:


    def self.up
      add_column :profiles, :last_name, :string
      add_column :profiles, :first_name, :string
      Profile.remove_class(Profile)
      load('profile.rb')
      Profile.find(:all).each do |profile|
        profile.first_name = profile.name
        profile.save(false)
      end
      remove_column :profiles, :name
    end

    现在,name就可以被正确的迁移到first_name字段中了,这个方法也可以用于在Console中重新加载某个过期的model。

    来源:www.letrails.cn

  • 相关阅读:
    php知识点
    CommonsChunkPlugin知识点
    待学习
    svn知识点
    es6知识点
    webpack2新特性
    排序算法
    交流措辞
    js继承
    多行编辑软件
  • 原文地址:https://www.cnblogs.com/ToDoToTry/p/2127950.html
Copyright © 2020-2023  润新知