搜索值范围栏

时间:2017-11-24 09:16:52

标签: ruby-on-rails

如何在范围中添加其他搜索值并将其添加到terms.map 并将其传递给where查询,我想要min和max值?

  scope :search_query, lambda { |query|
  return nil  if query.blank?

  # condition query, parse into individual keywords
  terms = query.downcase.split(/\s+/)

  # replace "*" with "%" for wildcard searches,
  # append '%', remove duplicate '%'s
  terms = terms.map { |e|
    (e.gsub('*', '%') + '%').gsub(/%+/, '%')
  }
  num_or_conds = 2
  where(
    terms.map { |term|
      "(LOWER(students.first_name) LIKE ? OR LOWER(students.last_name) LIKE ?)"
    }.join(' AND '),
    *terms.map { |e| [e] * num_or_conds }.flatten
  )
}

我想做什么

.where(column_name BETWEEN #{value1} AND #{value2})

1 个答案:

答案 0 :(得分:1)

您可以通过重复调用where来链接rails中的范围:

Thing.where(a: 1).where(b: 2)
# SELECT things.* FROM things WHERE things.a = ? AND things.b = ?

您还可以使用.merge合并范围:

Thing.where(a: 1).merge(Thing.where(b: 2))

使用range创建BETWEEN查询:

Thing.where(foo: (1..10))
# SELECT things.* FROM things WHERE foo BETWEEN 1 AND 10

这也适用于日期和时间。

scope中要记住的另一件事是类方法的语法糖。因此,如果你的方法不适合单行,你应该使用" classic"方法定义:

class Student < ApplicationRecord
  def self.search_query(query)
    scope = self.all

    terms = query.downcase.split(/\s+/)
    terms = terms.map { |e|
      (e.gsub('*', '%') + '%').gsub(/%+/, '%')
    }

    self.all.tap do |scope|
      terms.each do |term|
        scope.merge(
          self.where("(LOWER(students.first_name) LIKE :t OR LOWER(students.last_name) LIKE :t)", t: term)
        )
      end
    end
  end
end