どうもこんにちは。
今回は、動的にDBのテーブルにカラムを追加する方法をメモしていきます。
動的にカラムを追加とは?
本来であれば、DBのテーブルにカラムを追加する場合には、以下のような手順を踏むと思います。
- マイグレーションファイル生成
rails g migration AddNewColumnToSample
- マイグレーションファイル編集
class AddNewColumnToSample < ActiveRecord::Migration[7.0]
def change
# addcolumn :テーブル名, :カラム名, :データ型
add_column :samples, :new_column, :string
end
end
- マイグレーション実行
rails db:migrate
しかし、「custom_itemsテーブルにデータが登録された場合に、登録されたデータの名前でsamplesテーブルにカラムを追加したい」ということが出てきます。(複雑なアプリケーションの場合はアリエル)
そんなときに使える方法を紹介します。
手順
1. custom_itemsテーブルにデータを登録するアクションを作成
def create
@custom_item = CustomItem.new(name: params[:name])
if @custom_item.save
redirect_to custom_items_path
else
render :new
end
end
2. マイグレーションコードを追加
def create
@custom_item = CustomItem.new(name: params[:name])
if @custom_item.save
# ここを追加
ActiveRecord::Migration.add_column :sample, @custom_item.name, :string
# not nullにする場合には、ActiveRecord::Migration.add_column :sample, @custom_item.name, :string, null: false
redirect_to custom_items_path
else
render :new
end
end
3. Railsコンソールを起動してテーブルを確認する
rails c
Sample
これでテーブルにカラムが追加されます。
カラムを削除する場合の手順
1. custom_itemsテーブルからデータを削除アクションを作成
def destroy
@custom_item = CustomItem.find(params[:id])
if @custom_item.destroy
redirect_to custom_items_path
else
render :edit
end
end
2. マイグレーションコードを追加
def destroy
custom_item_name = @custom_item.name
@custom_item = CustomItem.find(params[:id])
if @custom_item.destroy
# ここを追加
ActiveRecord::Migration.remove_column :sample, custom_item_name
redirect_to custom_items_path
else
render :edit
end
end
3. Railsコンソールを起動してテーブルを確認する
rails c
Sample
これでテーブルにカラムからカラムが削除されます。
以上