【Rails】ArticlesController の各アクションをきちんと理解したい。
こんにちは。
rails初学者です。覚えては忘れ、覚えては忘れの繰り返しです。
再度、振り返れるように備忘録を残します。
今回は、ArticlesController を作成した後の、 「各アクションがどんな役割をしているのか?」 「よく見る render :new, status: :unprocessable_entity
って何?」 「private
とarticle_params
について」となります。
完成したコントローラー
以下、全体像
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to article_path(@article)
else
render :new, status: :unprocessable_entity
end
end
private
def article_params
params.require(:article).permit(:title, :content)
end
end
上記のコードの意味をまとめる
index
アクション
def index
@articles = Article.all
end
- 記事一覧を全部取り出すアクション
-
Article.all
でDBにある全レコードを取る - なぜ
@articles
は「複数形」なのかと思いましたが、全部まとめて取得するから複数形です
show
アクション
def show
@article = Article.find(params[:id])
end
- 1つの記事だけを取り出すアクション
-
params[:id]
に入っているIDを使って、特定のレコードを探す -
find
は、該当データがなかったらエラー -
params
は、URLに埋め込まれてるデータ (ex: /articles/1 なら id=1) を拾うもの
new
アクション
def new
@article = Article.new
end
- 空っぽの Article オブジェクトを作るだけ
- 「新規作成フォーム」に渡すために使う
- なんで保存しないのにnewをするのは、あくまで「フォーム表示用」で、保存はしてないから
create
アクション
def create
@article = Article.new(article_params)
if @article.save
redirect_to article_path(@article)
else
render :new, status: :unprocessable_entity
end
end
- フォームから送られてきたデータを使って、新しい記事を保存する
-
@article.save
が成功したら、その記事の詳細ページに飛ぶ
render :new, status: :unprocessable_entity
について
render :new
→ フォームのページ (new.html.erb) をもう一回表示
status: :unprocessable_entity
→ HTTPステータスコード422を返す
(「入力ミスで保存できなかったよ」 っていう意味をサーバー側で伝えるため)
redirect_to
と何が違うのか
-
redirect_to
はブラウザに「URL変えて!」と命令をする - しかし、
render
は「今のURLのまま」ページを表示 - 失敗したら元の「新規投稿フォーム」の画面を出して、エラーを見せたい
private
とarticle_params
について
private
def article_params
params.require(:article).permit(:title, :content)
end
-
private
から以下は「外部から呼び出さないメソッド」 -
article_params
は、フォームから送られてきたデータの中から 必要なもの (titleとcontent) だけを抜き出す - セキュリティ対策で、勝手に変なパラメータ送られるのを防ぐため
まとめ
-
index
→ 全部取ってくる -
show
→ 1個取ってくる -
new
→ 空っぽオブジェクト作る -
create
→ 保存を試みる。失敗したらrender :new, status: :unprocessable_entity
-
article_params
→ セキュリティのため、取り出すデータを制限する
わからないときは、「何をしたいか」に着目していきます。
間違えていたら、すいません。