LoginSignup
2
2

More than 5 years have passed since last update.

Rails tableのカラム名を変更

Last updated at Posted at 2018-04-28

やること  投稿フォーム、カラム修正する。

Contentをsentenceに修正。
モデル名 articles

スクリーンショット 2018-04-26 20.07.14.png

参考にしたページ
【備忘録】Rails-カラム名を変更する方法
https://qiita.com/kaito-chiba/items/723da8627438b67cc02c

 ファイル作成

migrationファイル作成。

$ rails generate migration rename_content_column_to_articles

 編集する

下記ファイルが作成される

db/migrate/20180427005336_rename_content_column_to_articles.rb
class RenameContentColumnToArticles < ActiveRecord::Migration[5.0]
  def change

  end
end

次のように変更する

db/migrate/20180427005336_rename_content_column_to_articles.rb
class RenameContentColumnToArticles < ActiveRecord::Migration[5.0]
  def change
    rename_column :articles, :content, :sentence
  end
end

rename_column :テーブル名 , :変更前のカラム名, :変更後のカラム名

 データベースに反映させる。

$ rake db:migrate

これで、大丈夫。

あとは、viewsなどを修正していく。

スクリーンショット 2018-04-28 10.48.53.png

 番外

  1. generateコマンド取り消し方法
$ rails destroy migration rename_content_column_to_articles

db/migrate/20180427005336_rename_content_column_to_articles.rbファイルの修正を間違えたため、コマンドを取り消してみた。

2. カラム名は、日本語にしないほうが良い
参考にしたページ
https://qa.atmarkit.co.jp/q/2207

 最後に。

もし、何か間違いなどありましたら、ご指摘いただけると幸いです。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2