Techioz Blog

Ruby on Railsは特定の列名の後に列を追加します

概要

テーブル内の特定の列の後に列を追加しようとしました。 私がやったことは次のとおりです。

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

何か見逃した場合は誰かが教えてくれますか?コマンドがうまくいったとは思えません。上記のファイルに「=」が表示されています。そこにあるべきではないと思います。

もしそうなら、どうすれば上記を元に戻せますか?

解決策

実際にこの移行を Rails db:Migrate できるとは思えないので、ロールバックする必要はありません。下の 3 つの add_columns を削除し、上の 1 つを次のように置き換えるだけです。

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

移行しても問題ないはずです。将来の参考のために、入力したコマンドは次のようになります。

rails generate migration add_reaction_id_to_patient_allergies reaction_id:integer

整数の前にスペースがあると、ジェネレーターはそれが新しい列であると認識しました。残念ながら、コマンドラインでも Ruby 構文 (a => b) を使用することはできません。