1
0

More than 1 year has passed since last update.

【Rails】ControllerのParamの有無でWhere条件をつけたりつけなかったりする方法

Last updated at Posted at 2021-12-09

これは「「はじめに」の Advent Calendar 2021」9日目の記事です。

1. モデルにScopeを追加

scopeの filter_name_byname を渡せるようにし、 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
1
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
1
0