これは「「はじめに」の Advent Calendar 2021」9日目の記事です。
1. モデルにScopeを追加
scopeの filter_name_by
に name
を渡せるようにし、 name
が存在するときに条件がセットされるようにします。
class Foo < ApplicationRecord
has_many :barz
end
class Bar < ApplicationRecord
belongs_to :foo
scope :filter_name_by, -> (name) { where(name: name) if name.present? }
end
2. ControllerのParamをそのまま渡す
controllerではparamsをそのまま渡せます。
class BarController < ApplicationController
def index
bars = Bar.filter_name_by(params[:name])
render json: bars
end
end
nameがあるときのSQLは
SELECT * FROM bars WHERE bars.name = ?
nameがないときのSQLは
SELECT * FROM bars
3. Fooと子テーブルとしてBarを検索したい場合にBarに条件を追加する場合
include, referencesと一緒にmergeを使うそうです。
class FooController < ApplicationController
def index
foos = Foo.includes(:bars).merge(Bar.filter_name_by(params[:name])).references(:bars)
render json: foos
end
end