#基本的なCRUD
MythreadControllerを例に
Create->新規作成(new, create)
Read->データ一覧・個別の表示(index, show)
Update->データの更新(edit, update)
Delete->データの削除(delete)
の機能を持つコントローラを考えます。
Viewは以下があるという認識で。
- データの一覧の表示 index.ctp
- 個別データの表示 show.ctp
- 新規作成ページの表示 new.ctp
- 編集ページの表示 edit.ctp
MyTreadsController
class MyThreadsController < ApplicationController
#before_actionで各メソッドを呼び出す前にメソッドを呼び出す
#onlyでどのメソッドで呼び出すか制限をかける
before_action :set_my_thread, only: [:show,:update,:edit,:delete]
#index->データの一覧の表示
def index
#mythreadのデータの全件取得
@my_threads = MyThread.all
end
#show->個別データの表示
def show
#before_actionでデータの取得は完了している
end
#new->新規作成ページの表示
def new
#モデルオブジェクトの生成
@my_threads = MyThread.new
end
#create->新規データの登録
def create
#formのデータを受け取る
@my_threads =MyThread.create(my_thread_params)
#saveメソッドでデータをセーブ *newメソッド + saveメソッド = createメソッド
if @my_threads.save
#saveが完了したら、一覧ページへリダイレクト
redirect_to my_threads_path
else
#saveを失敗すると新規作成ページへ
render 'new'
end
end
#edit->編集ページの表示
def edit
#before_actionでデータの取得は完了している
end
#update->編集のアップデート
def update
#編集データの取得
if @my_threads.update(my_thread_params)
#updateが完了したら一覧ページへリダイレクト
redirect_to my_threads_path
else
#updateを失敗すると編集ページへ
render 'edit'
end
end
#destroy->データの削除
def destroy
#データの削除
@my_threads.destroy
#一覧ページへリダイレクト
redirect_to my_threads_path
end
private
#strong parameters リクエストパラメターの検証(これがないとうまくいかないので注意)
def my_thread_params
params.require(:my_thread).permit(:title)
end
#共通処理なので、before_actionで呼び出している
def set_my_thread
#特定データの取得
@my_threads = MyThread.find(params[:id])
end
end