我有一个教师模型和一个学生模型(老师有很多学生)。希望使用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
)
}
答案 0 :(得分:2)
我从我使用includes
而不是joins
的方案中获取了示例代码,因为我需要一个正确的外连接。在这种情况下,我必须让Rails知道我正在引用学生表。
我不确定您是否确实需要references
部分joins
。试试看没有,我很想知道它是否有效。
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)
}