【问题标题】:Updating Attribute Value in Rails Migration在 Rails 迁移中更新属性值
【发布时间】:2015-06-27 22:44:55
【问题描述】:

我通过 ActiveAdmin (http://activeadmin.info/) 上传了 100 多个具有以下属性的食谱:

class CreateRecipes < ActiveRecord::Migration
  def change
    create_table :recipes do |t|
      t.string :title
      t.string :description
      t.string :ingredients
      t.string :position

      t.timestamps
    end
  end
end

我需要将位置从字符串更改为整数。我可以通过以下方式做到这一点:

change_column :table_name, :column_name,  :integer  

stackoverflow:Rails migration for change column

问题是我不知道如何返回并重新为所有配方分配一个位置(现在它是一个整数)。我基本上想从 0 开始一直到 100。如果我创建一个新配方,它会自动具有 101 的位置值。

有没有办法在不返回并单独更改每个配方的情况下做到这一点?

【问题讨论】:

    标签: ruby-on-rails migration


    【解决方案1】:

    听起来您最初想将:position 设置为:id。您可以像这样通过 rails 控制台做到这一点:

    recipes = CreateRecipes.all
    recipes.each do |recipe|
      recipe.position = recipe.id
    end
    

    然后,对于新配方,在您的模型 (create_recipes.rb) 中,您可以添加:

    after_initialize :default_values
    ...
    def default_values
      self.position ||= id
    end
    

    顺便说一句,这是一种处理默认值或初始值的好方法。有关更多信息,请参阅这篇出色的帖子 How can I set default values in ActiveRecord?

    【讨论】:

      【解决方案2】:

      您可以让转换作为迁移本身的一部分自动运行。添加代码以将现有记录中的值转换为迁移。使用 self.up 和 self.down 来获得适合该迁移方向的转换代码:

      class ChangeRecipePositionToInteger < ActiveRecord::Migration
        def self.up
          position_values = Hash[ Recipe.all.map{|r| [r.id, r.position]}]
      
          change_column :recipes, :position, :integer
      
          position_values.each_pair do |id, position_value|
            recipe = Recipe.find( id )
            recipe.position = position_value.to_i
            recipe.save
          end
        end
      
        def self.down
          position_values = Hash[ Recipe.all.map{|r| [r.id, r.position]}]
      
          change_column :recipes, :position, :string
      
          position_values.each_pari do |id, position_value|
            recipe = Recipe.find( id )
            recipe.position = position_value.to_s
            recipe.save
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2018-04-20
        • 1970-01-01
        • 1970-01-01
        • 2017-05-27
        • 2023-04-05
        • 2016-02-06
        • 2011-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多