Rails 迁移删除行

Rails migration delete row

我正在尝试 运行 迁移以删除数据库中的两行。这是迁移文件...

class RemoveMenuItem < ActiveRecord::Migration
  def up
    MenuItem.delete(name: "Validation Settings")
    MenuItem.delete(name: "Identifier Lookup")
  end

  def down
    MenuItem.create(name: "Validation Settings", type: "MenuItem", actionable_item_id: 89, actionable_items_count: 0, sequence: 20)
    MenuItem.create(name: "Identifier Lookup", type: "MenuItem", actionable_item_id: 89, actionable_items_count: 0, sequence: 30)
  end
end

...但我收到此错误...

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "id"
LINE 1: ...ERE "actionable_items"."type" IN ('MenuItem') AND "id"."name...
                                                             ^
: DELETE FROM "actionable_items" WHERE "actionable_items"."type" IN ('MenuItem') AND "id"."name" = 'Validation Settings'/Users/kweihe/.rvm/gems/ruby-2.1.6/gems/activerecord-3.2.22/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'

删除需要识别的记录才能工作。试试这个:

 def up
      MenuItem.find_by(name: "Validation Settings").delete
      ....

虽然我同意评论者的观点 - 这似乎不是您在迁移中必然想要的东西。在种子文件中可能更好。

解决方案

class RemoveActionableItems < ActiveRecord::Migration
  class ActionableItem < ActiveRecord::Base
    attr_accessible :actionable_item, :name, :sequence, :type
  end
  def up
    validation_settings = MenuItem.find_by_name("Validation Settings")
    identifier_lookup = MenuItem.find_by_name("Identifier Lookup")
    compliance = InsightReportMenuItem.find_by_name("Compliance")
    validation_settings.delete unless validation_settings.nil?
    identifier_lookup.delete unless identifier_lookup.nil?
    compliance.delete unless compliance.nil?
  end

  def down
    MenuItem.create :name => "Validation Settings", :type => "MenuItem"
    MenuItem.create :name => "Identifier Lookup", :type => "MenuItem"
    InsightReportMenuItem.create :name => "Compliance", :type => "InsightReportMenuItem"
  end
end