【问题标题】:Run migration with data update after model code changed模型代码更改后使用数据更新运行迁移
【发布时间】:2017-05-24 10:36:54
【问题描述】:

我有一个名为Restream::Custom 的模型和一个属性url。然后我想将url 属性一分为二:server_urlkey,并且都需要。 我为此编写了这样的迁移:

def up
    add_column :restream_customs, :key, :string

    Restream::Custom.find_each do |r|
      last_slash = r.url.rindex("/")
      r.key = r.url[last_slash + 1 .. -1] #everything after last slash
      r.url = r.url[0 .. last_slash - 1] #everything before last slash
      r.save!
        end

    change_column :restream_customs, :key, :string, null: false
    rename_column :restream_customs, :url, :server_url
end

这在开发中效果很好。之后,我在restream/custom.rb 中进行了很多更改,以便与server_url 一起工作并对其进行验证。 并且此迁移因此在暂存时失败(并且将在生产中失败),因为在运行r.save! 时,它面临validates :server_url, presence: true 并抛出unknown attribute 'server_url' for Restream::Custom

我能做些什么来正确地进行这些更改?如果可能的话,转一圈。 (不要多次从 repo 中提取)。

【问题讨论】:

    标签: ruby-on-rails rails-migrations


    【解决方案1】:

    在更新数据之前尝试将列 url 重命名为 server_url

    def up
      add_column :restream_customs, :key, :string
      rename_column :restream_customs, :url, :server_url
    
      Restream::Custom.find_each do |r|
        last_slash = r.server_url.rindex("/")
        r.key = r.server_url[last_slash + 1 .. -1] #everything after last slash
        r.server_url = r.server_url[0 .. last_slash - 1] #everything before last slash
        r.save!
      end
    
      change_column :restream_customs, :key, :string, null: false
    end
    

    【讨论】:

    • 那……显然很棒!谢谢!但是仍然存在一个问题:我的custom.rb 中还有一个validates :key, presence: true 会引发同样的错误:(
    • 好像有些网址不包含key
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 2018-02-24
    • 2014-06-23
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多