76
64

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 5 years have passed since last update.

部分一致とか日付の範囲で検索したい

Posted at

課題メモより

部分一致検索

部分一致に限ったことではないのですが、モデルクラスのscopeでクラスメソッドを作成しておくと、他の検索条件と組み合わせる時に便利です。

app/model/employee.rb
class Employee < ActiveRecord::Base
  scope :name_like, -> name {
    where('name like ?', "%#{name}%") if name.present?
  }
end
使い方
Employee.name_like('佐藤')

日付の範囲で検索

app/model/employee.rb
class Employee < ActiveRecord::Base
  scope :birth_between, -> from, to {
    if from.present? && to.present?
      where(birth: from..to)
    elsif from.present?
      where('birth >= ?', from)
    elsif to.present?
      where('birth <= ?', to)
    end
  }
end
使い方
Employee.birth_between('2000/01/01', '2000/12/31') #=> 範囲指定で検索
Employee.birth_between('2000/01/01', nil         ) #=> from以降を検索
Employee.birth_between(nil         , '2000/12/31') #=> to以前を検索
Employee.birth_between(nil         , nil         ) #=> 全件を返す

複数の条件で検索

scopeを定義しておくと便利なのは、メソッドチェーンで定義したメソッドを組み合わせて複数の条件を簡単に作れることです。
上の2つを組み合わせて以下のように書くことができます。

app/model/employee.rb
class Employee < ActiveRecord::Base
  scope :name_like, -> name { ... } #(略)
  scope :birth_between, -> from, to { ... } #(略)

  # cond: 検索条件入力フォームのモデルオブジェクト
  scope :match -> cond {
    name_like(cond.name).birth_between(cond.birth_from, cond.birth_to)
  }
end

76
64
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
76
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?