2
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?

More than 3 years have passed since last update.

Ransackで全角半角跨いだの検索を行う

Last updated at Posted at 2021-03-24

600 Contributions達成記念

TL;DR

入力されたキーワードを加え、全角、半角バージョンを追加して、_anyをつけて検索します。

User.ransack({name_cont_any: ['テストテスト123abC', 'テストテスト123abC', 'テストテスト123abC']})

全角<=>半角変換

英数字

半=>全

"abc123".tr('0-9a-zA-Z', '0-9a-zA-Z')
=> "abc123"

全=>半

"123abC".tr('0-9a-zA-Z', '0-9a-zA-Z')
=> "123abC"

カタカナ

全=>半

require 'nkf'

NKF.nkf('-w -x -Z4', 'イロハ')
=> "イロハ"

半=>全

NKF.nkf("-w -X", "イロハ")
=> "イロハ"

OR検索

こんなレコードがあると仮定します

#<User id: 1, family_name: "実験", first_name: "花子", family_name_kana: "ジッケン", first_name_kana: "ハナコ">

名前の仮名が全角か半角かは決められない場合、全てのハナコさんを検索したい場合、検索キーワードを上記の手法で全角1セット、半角1セットを用意して、下記のRansack述語(Predicate)で検索できます

User.ransack({ family_name_kana_or_first_name_kana_cont_any: ['ハナコ', 'ハナコ'] }).result
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE (("users"."family_name_kana" ILIKE '%ハナコ%' OR "users"."family_name_kana" ILIKE '%ハナコ%') OR ("users"."first_name_kana" ILIKE '%ハナコ%' OR "users"."first_name_kana" ILIKE '%ハナコ%'))

参考

おまけ

全角⇔半角の変換を行う(英数字、カタカナ)で紹介された英数字の全半角変換アルゴリズムをRubyでアレンジしました。

# 半角英数字 => 全角英数字
"abc123".gsub(/[a-zA-Z0-9]/){|c| (c.ord + 0xFEE0).chr }
=> "abc123"

# 全角英数字 => 半角英数字
"123abC".gsub(/[a-zA-Z0-9]/){|c| (c.ord - 0xFEE0).chr }
=> "123abC"
2
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
2
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?