【问题标题】:ruby on rails add a column after a specific column nameruby on rails 在特定列名之后添加一列
【发布时间】:2013-03-07 01:54:06
【问题描述】:

我尝试在表格中的特定列之后向表格中添加一列。 这是我所做的:

rails generate migration add_reaction_id_to_patient_allergies reaction_id: integer :after => 'patient_id'

这是我的迁移文件的样子:

class AddReactionIdToPatientAllergies < ActiveRecord::Migration
  def change
    add_column :patient_allergies, :reaction_id, :string
    add_column :patient_allergies, :integer, :string
    add_column :patient_allergies, :, :after
    add_column :patient_allergies, :=, :string
  end
end

我认为命令进行得并不顺利。我在上面的文件中看到了一个“=”。我认为它不应该在那里。如果我遗漏了什么,有人可以告诉我吗?

如果是这样,我该如何撤消上述操作?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2


    【解决方案1】:

    我怀疑它是否允许您实际 rake db:migrate 此迁移,因此您不必回滚。只需删除底部的三个add_columns 并将顶部的替换为

    add_column :patient_allergies, :reaction_id, :integer, after: :patient_id
    

    迁移应该没问题。为了将来参考,您输入的命令应如下所示:

    rails generate migration add_reaction_id_to_patient_allergies reaction_id:integer
    

    integer 之前的空格让生成器认为这是一个新列。遗憾的是,您也不能在命令行上使用 Ruby 语法 (a =&gt; b)。

    【讨论】:

    • @michael 只是为这个出色的答案再添加一件事,要撤消成功但不需要的迁移,您可以执行 rake db:rollback - 这与最近的迁移相反。您可以通过重复它来进一步退后。我经常发现自己无法进行一些小的调整,例如设置默认值或列顺序
    • :after 选项看起来不包含在 API documentation 中,至少对于 Rails 4.2.3 而言。尝试后发现:迁移成功但未应用排序。
    • @nandinga 看起来最新 Rails 中的 ColumnDefinition 类仍然支持 after 选项,尽管我还没有在 Rails 的最后几个版本中测试过。
    • 显然,如果您使用的是 Postgres,这将不起作用。见dba.stackexchange.com/questions/3276/…
    猜你喜欢
    • 2020-03-08
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2013-07-06
    • 2011-12-17
    相关资源
    最近更新 更多