2
0

More than 1 year has passed since last update.

【Ruby】Railsでリクエストのバリデーションを行うライブラリ`rails_param`

Last updated at Posted at 2022-08-23

概要

Railsでリクエストのバリデーションを行う場合、Rails基礎 ストロングパラメータとバリデーションの記事にある通り、ApplicationRecordの機能を使用する方法などが挙げられます。もちろん、この方法でも全然良いのですが、ApplicationRecordのモデルに通す前に、controllerでバリデーションしたい時もあるなと感じました。
何かないかなと調べてみた結果、rails_paramというライブラリが良さげだったので、今回少し紹介します。

機能など

nicolasblanco/rails_paramに、ライブラリのReadmeがあります。パラメータの、型指定や、必須チェック、最小値・最大値など基本的なチェックは出来そうです。また、項目毎にエラーのメッセージもカスタムで設定できます。

実装サンプル

以下はAPIで、文字列の必須・ブランクチェックを、controllerに実装したサンプルです。
必須チェックでエラーの場合は、Parameter sample_word is requiredのようなメッセージをデフォルトで返してくれます。

class SampleController < ApplicationController

  def validate_sample
    # バリデーションの設定
    param! :sample_word, String, required: true, blank: false
    
    puts(params[:sample_word])
    render status: :ok
  # バリデーションNGの場合
  rescue InvalidParameterError => e
    render status: :bad_request, json: { message: e }
  rescue StandardError => e
    render status: :internal_server_error, json: { message: e }
  end
end
2
0
1

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