LoginSignup
0
0

Rails – ActiveRecordのメソッドチェーンで then を使って nil 対策 ( 変数の値の有無で処理分岐 )

Posted at

問題

  • 変数の値がある時はその値で絞り込みたい
  • 変数の値が nil の時は何も絞り込みをおこないたくない

だが次のような書き方だと カラムの値が NULL のものを絞り込んでしまう

target_id = nil

User.where(flag: true).where(id: target_id)

解決

then を使って分岐させる

target_id = nil

User.where(flag: true).then do |relation|
  if target_id
    relation.where(id: target_id)
  else
    relation
  end
end

scope でも実現できるがこちらの方が手軽な書き方

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

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