0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails初学者】ArticlesController の各アクション備忘録など

Last updated at Posted at 2025-04-29

【Rails】ArticlesController の各アクションをきちんと理解したい。

こんにちは。
rails初学者です。覚えては忘れ、覚えては忘れの繰り返しです。
再度、振り返れるように備忘録を残します。
今回は、ArticlesController を作成した後の、 「各アクションがどんな役割をしているのか?」 「よく見る render :new, status: :unprocessable_entityって何?」 「privatearticle_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のまま」ページを表示
  • 失敗したら元の「新規投稿フォーム」の画面を出して、エラーを見せたい

privatearticle_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→ セキュリティのため、取り出すデータを制限する

わからないときは、「何をしたいか」に着目していきます。
間違えていたら、すいません。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?