2
0

More than 1 year has passed since last update.

[Rails] action_argsでparamsを操る

Last updated at Posted at 2022-11-03

はじめに

action_argsがparamsを扱う上で流行っているらしい。
さっそく使ってみる。

確認環境

Ruby 3.1.2
Rails 6.1.7

導入

# Gemfileに以下を追加
gem 'action_args' 

# インストール
$ bundle install

使い方

showアクションとcreateアクションを例にとってご紹介します。

showアクション

通常のparamsの場合

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end
end

そうです。params[:id]によってuserのidを取得します。

action_argsの場合

class UsersController < ApplicationController
  def show(id)
    @user = User.find(id)
  end
end

アクションに対してparams[:id]と同義となる引数idを渡すことで、このアクションで必要とされるパラメータが明確になります。この場合、idは必須パラメータとなり、paramsに存在しない場合ActionContrrler::BadRequestが発生します。

引数を任意とする場合

class ProductsController < ApplicationController
  def index(price, kind: nil)
    @products = Prodcut.where(price: price, kind: kind)
  end
end

kind: nilによってkindは任意となり、paramsに存在しなくともエラーが発生することはありません。
注意:コードはあくまで例です。

createアクション

通常のparamsの場合

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    
    if @user.save
      redirect_to @user
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:name)
  end
end

通常はprivateにuser_paramsメソッドを定義しストロングパラメータを設定しますよね。

action_argsの場合

class UsersController < ApplicationController
  permits :name

  def create(user)
    @user = User.new(user)
    
    if @user.save
      redirect_to @user
    else
      render :new
    end
  end
end

action_argsの方が全体的にスッキリしていますね。
先頭に許可するパラメータを宣言し、コントローラ名から推測されるuserにより登録するパラメータを渡しています。
user_paramsとしても同様に働くため、プロジェクト途中での導入も修正が少なく済みそうです。

関連モデルへのストロングパラメータ対応

model_nameを指定することで、Usersコントローラ内でProductモデルの属性を許可することもできます。引数として渡すproductは、前述の通りproduct_paramsでも代用可能です。

class UsersController < ApplicationController
  permits :name, model_name: 'Product'

  def create(product)
    @prodcut = Product.new(product)

      if @prodcut.save
        redirect_to @prodcut
      else
        render
      end
  end
end

Eventコントローラ内でネストしたParticipantモデルの属性も許可する場合も問題なしです。(accepts_nested_attributes_for対応)

class EventsController < ApplicationController
  permits :name, :price, 
    participants_attributes: [:id, :name, :_destroy]
end

最後に

いかがでしたでしょうか。
導入の是非はプロジェクトによって変わると思いますが、試してみてもいいかもしれません。
その他の使い方についてはaction_argsのGitHubを参照してください。

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