Ruby on rails 需要在迁移中更新属性

Ruby on rails 需要在迁移中更新属性,ruby-on-rails,migration,Ruby On Rails,Migration,我正在尝试使用下面的迁移添加一条记录,然后用新记录id更新4条其他记录。新记录添加良好,但更新未发生 def change ItemsCategory.reset_column_information hub = ItemsCategory.create name: 'HUB RECORD' ItemsCategory.where(id: 1..4).each do |p| p.update_attribute :parent_id, hub.id

我正在尝试使用下面的迁移添加一条记录,然后用新记录id更新4条其他记录。新记录添加良好,但更新未发生

  def change

    ItemsCategory.reset_column_information

    hub = ItemsCategory.create name: 'HUB RECORD'

    ItemsCategory.where(id: 1..4).each do |p|
      p.update_attribute :parent_id, hub.id
      p.save
    end

    ItemsCategory.build_ancestry_from_parent_ids!
  end

您不应该在迁移中更改内容。迁移专门用于更改您的架构。内容迁移是一种反模式。您应该使用定制的rake任务来处理内容。

Sean是100%正确的。您不应该使用迁移来修改表内容,而应该只修改模式。使用自定义rake任务来执行此操作。让我给你举个例子

使用命令rake db:color加载颜色表将是:

将此代码放在lib/tasks/color.rake中:

namespace "db" do
  desc "Load Color  database"
  task color: :environment do |t|
    APP_PATH = File.expand_path('../../../db', __FILE__)
    puts "Running #{APP_PATH}/color.rb"
    require "#{APP_PATH}/color"
  end
end
将此代码放在db/color.rb中:

# Run from lib/tasks/color.rake using:
# rake db:color
# or with tools/rake
Color.delete_all
colors = ["Black", "White", "Silver", "Red", "Blue", "Green", "Other"]
colors.each do |c|
 Color.create color: c
end

可能您的条件ID:1..4没有从DB返回任何对象?试试ItemsCategory.order:id.limit4.update_allparent_id:hub.idI会试试的,但我在里面放了一个puts来确认它击中了那些记录!回答一下,我会记下来的。谢谢