Rails迁移删除行

时间:2015-07-17 21:54:16

标签: ruby-on-rails ruby-on-rails-3 migration delete-row migrate

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

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'

2 个答案:

答案 0 :(得分:2)

删除需要已识别的记录才能生效。试试这个:

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

我同意评论者的意见 - 这似乎不是您在迁移中必然要做的事情。在种子文件中可能更好。

答案 1 :(得分:0)

<强>解

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