はじめに
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を参照してください。