【问题标题】:Rails 5: How to remove a column from a database?Rails 5:如何从数据库中删除列?
【发布时间】:2016-12-13 16:42:47
【问题描述】:

使用迁移从表中删除现有列的命令是什么?

我要删除的列是:country:string

来自表:sample_apps

【问题讨论】:

  • 嗨,欢迎来到 Stack Overflow!我看到你的问题已经有了答案,但我想我应该让你知道,对 Rails 有一个很好的基本了解的最好的地方之一是官方的 Rails 指南:edgeguides.rubyonrails.org - 它们的可读性非常好,可以帮助你升级超级快速地了解您对 Rails 的基本理解。专门针对迁移的一个是:edgeguides.rubyonrails.org/active_record_migrations.html,但我也建议从头开始阅读它们。 :)

标签: ruby-on-rails


【解决方案1】:

使用迁移移除列:

rails g migration Remove..From.. col1:type col2:type col3:type

在你的情况下:

rails g migration RemoveCountryFromSampleApps country:string

这将在 Rails 5.0 中生成以下迁移:

class RemoveCountryFromSampleApps < ActiveRecord::Migration[5.0]
  def change
    remove_column :sample_apps, :country, :string
  end
end

【讨论】:

  • 我需要在这之后运行rails db:migrate吗?
  • 再澄清 1 点。由于模型名称 SampleApp 是单数,而表名 sample_apps 是复数,我应该使用哪一个? RemoveCountryFromSampleAppRemoveCountryFromSampleApps
  • 复数,刚刚编辑了我的答案 ^^' 以获得有关迁移的完整概述,您可以查看全新的 SO Documentation section
  • 这是可逆的吗?如果我运行 rails db:rollback 会发生什么?
【解决方案2】:

创建迁移文件:

$ rails generate migration RemoveCountryFromSampleApps country:string

在生成的迁移文件中:

class RemoveCountryFromSampleApps < ActiveRecord::Migration
 def change
   remove_column :sample_apps, :country, :string
 end
end

然后运行:

 rake db:migrate

【讨论】:

  • 在 Rails 5 中不再有 rakerails 调用。始终使用rails
【解决方案3】:

从表(sample_case)中删除一列(此处为国家)

rails generate migration RemoveCountryfromSampleCase country:string

上面的命令应该生成一个文件YYYYMMDDHHMMSS_remove_countryfrom_sample_case.rb。在 db/migrate 文件夹下

class RemoveCountryFromSampleCase < ActiveRecord::Migration[5.0]
  def change
    remove_column :sample_case, :country, :string
  end
end

在我的情况下(我做了两列以上)只有这个出现

 class RemoveCountryFromSampleCase < ActiveRecord::Migration[5.0]
  def change
  end
 end

remove_column 行不存在所以我手动添加它然后触发命令

rails db:migrate

它对我有用。

参考https://stackoverflow.com/a/2963582 & Active Record 迁移的 Ruby 指南 https://edgeguides.rubyonrails.org/active_record_migrations.html

【讨论】:

    【解决方案4】:

    如果也想删除索引,您也可以使用迁移:

    rails g migration remove_post_id_from_comments post_id:integer:index
    

    迁移文件:

    class RemovePostIdFromComments < ActiveRecord::Migration
      def change
        remove_index :comments, :post_id
        remove_column :comments, :post_id, :integer
      end
    end
    

    然后运行:rake db:migrate

    【讨论】:

    【解决方案5】:

    需要指定类型吗?

    这里的示例为什么不只是remove_column :sample_apps, :countryremove_column :comments, :post_id?似乎工作并消除了出错的机会(文本或字符串)。

    【讨论】:

    • 在我的版本中不会产生错误,它只是一种模式。如果类型参数与原始类型不同,则类型参数不会产生问题。
    • 您需要具体说明类型,以防您需要回滚
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 2016-09-27
    相关资源
    最近更新 更多