Lチカ開発ブログ

https://l-chika.com/の開発ブログ

ActiveRecordでMySQLの正規表現(REGEXP)

ActiveRecordを利用して、MySQLのREGEXPを利用したい場合

class Book < ActiveRecord::Base
  scope :with_title_regexp, -> (pattern) { with_regexp(columns_hash['title'].name, pattern) }
  scope :with_regexp, -> (column, pattern) { where("`#{table_name}`.`#{column}` REGEXP ?", pattern) }
end

こうすると、以下のように正規表現を利用した検索ができるようになる

Book.with_title_regexp('^[a-d]') #=> SELECT * FROM `books` WHERE (`books`.`title` REGEXP '^[a-d]');