sql - 在 Rails 中使用 Filterrific 搜索 Active Record 关联

标签 sql ruby-on-rails filterrific

我有一个教师模型和一个学生模型(教师有_许多学生)。希望使用 Filterrific 按学生姓名搜索教师。

filterrific 的默认功能是根据对教师表的 SQL 查询来搜索教师。

我想知道如何根据教师协会的表格来搜索教师。这是teacher.rb中的SQL代码:

 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(/%+/, '%')
    }
    # configure number of OR conditions for provision
    # of interpolation arguments. Adjust this if you
    # change the number of OR conditions.
    num_or_conditions = 3
    where(
      terms.map {
        or_clauses = [
          "LOWER(teachers.first_name) LIKE ?",
          "LOWER(teachers.last_name) LIKE ?",
          "LOWER(teachers.email) LIKE ?"
        ].join(' OR ')
        "(#{ or_clauses })"
      }.join(' AND '),
      *terms.map { |e| [e] * num_or_conditions }.flatten
    )
  }

最佳答案

我从使用 includes 而不是 joins 的场景中获取了示例代码,因为我需要一个右外连接。在这种情况下,我必须让 Rails 知道我正在引用学生表。

我不确定您是否确实需要带有joinsreferences 部分。不尝试一下,我很想知道它是否有效。

scope :search_query_by_students, 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(/%+/, '%')
  }
  # configure number of OR conditions for provision
  # of interpolation arguments. Adjust this if you
  # change the number of OR conditions.
  num_or_conditions = 3
  where(
    terms.map {
      or_clauses = [
        "LOWER(students.first_name) LIKE ?",
        "LOWER(students.last_name) LIKE ?",
        "LOWER(students.email) LIKE ?"
      ].join(' OR ')
      "(#{ or_clauses })"
    }.join(' AND '),
    *terms.map { |e| [e] * num_or_conditions }.flatten
  ).joins(:students).references(:students)
}

关于sql - 在 Rails 中使用 Filterrific 搜索 Active Record 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429150/

相关文章:

ruby-on-rails-4 - 导轨,具有多个参数的过滤器

ruby-on-rails - Filterrific,没有参数和复选框的范围

ruby-on-rails - rails 属性名称驼峰式问题

ruby-on-rails - 在迁移 PostgreSQL 上设置主键值 0 并自动递增

ruby-on-rails - 有没有办法在带有 Mongoid 的 Rails 项目中默认设置 attr_accessible?

php - 新闻提要的 SQL 内部连接

sql - 根据组内索引更新列

sql - 查询以获取总行数和不同行数之间的差异

mysql - 匹配 MySQL 中的单词 "Different"( bool 模式)