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初学者】 Rails8のparams.expectでStrong Parametersがより簡潔になったみたい

Posted at

Rails初学者の備忘録として、Rails8から導入されたparams.expectについて記録します。
従来のrequire + permitの組み合わせに代わる新しい書き方を学んだので、忘れないようにまとめておきます。

今回学んだこと

Strong Parametersを書くときに、今までは以下のように書いていました

従来の書き方(Rails7以前)

def document_params
  params.require(:document).permit(:image, :doc_type)
end

新しい書き方(Rails8以降)

def document_params
  params.expect(document: %i[image doc_type])
end

なんと1行で書けるようになりました

新しい書き方のメリット

シンプルで分かりやすい

  • require + permitの2段階が1つのメソッドにまとまる
  • ハッシュ形式で書けるので、許可するパラメータが見やすい

セキュリティは変わらず安心

params.expectは内部的に従来のrequire + permitと同じ処理をしてくれるので、セキュリティレベルは同じのようです

Active Storage以外でも使える

Active Storageの例でよく見かけるので「ファイルアップロード専用?」と思ってしまいがちですが、普通のStrong Parametersでも使えます

実際に書いてみた例

今まで作っていたドキュメントアップロード機能のコントローラで実際に使ってみました

class DocumentsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_visit
  before_action :set_document, only: [ :edit, :update, :destroy ]

  def create
    @document = @visit.documents.build(document_params)
    @document.user = current_user
    if @document.save
      flash[:notice] = "画像をアップロードしました。"
      redirect_to visit_documents_path(@visit)
    else
      flash.now[:error] = "アップロードに失敗しました。"
      render :new, status: :unprocessable_entity
    end
  end

  private

  def set_visit
    @visit = current_user.visits.find(params[:visit_id])
  end

  # Rails8の新しい書き方
  def document_params
    params.expect(document: %i[image doc_type])
  end
end

配列パラメータの記述

# 従来
params.require(:post).permit(:title, tag_ids: [])

# Rails8
params.expect(post: [:title, tag_ids: []])

参考

params.expectの詳細な説明は以下で確認できます

まとめ

Rails 8のparams.expect

  • Strong Parametersの記述をより簡潔にする
  • 既存のrequire + permitと同等のセキュリティを提供
  • Active Storage以外のすべてのモデルで使用可能
  • 段階的な移行が可能

今後は、params.expectを使用していきたいと思います。
初学者のため、間違えていたらすいません。

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?