LoginSignup
0
0

More than 3 years have passed since last update.

【Rails】 姓・名それぞれがDBのカラムとして格納されているレコードの検索方法

Posted at

姓・名それぞれがDBのカラムとして格納されているレコードの検索方法

すでにたくさんの記事が出ていますが、自分がよく使うものを忘れないようにメモしました。

name = '山田 太郎'
scope = User.all

if name.include?(' ') || name.include?(' ')
    # 全角スペース を 半角スペース へ置き換え
    name = name.tr(' ', ' ') if name.include?(' ')
    # 姓・名を分割
    last_name, first_name = name.split(' ')
    # and 条件で検索
    scope = scope.where('last_name LIKE ? AND first_name LIKE ?', "%#{last_name}%", "%#{first_name}%")
else
    # 姓名どちらかのみ入力されている場合
    scope = scope.where('last_name LIKE :name OR first_name LIKE :name', name: "%#{name}%")
end

参考

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