我有一个教师模型和一个学生模型(教师有_许多学生)。希望使用 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 知道我正在引用学生表。
我不确定您是否确实需要带有joins
的references
部分。不尝试一下,我很想知道它是否有效。
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/