1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2020-12-22

姓・名それぞれが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

参考


会社紹介

株式会社 Mosaica
最先端テクノロジーで社会課題を解決し、持続可能な未来を創造する IT カンパニー。
AI ソリューション、クラウド統合、DX 推進、経営コンサルティングなど包括的なサービスでビジネス変革を支援しています。

詳しくは 公式サイト までお気軽にご相談ください。
公式サイト: https://mosaica.co.jp/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?