2015-05-24 134 views
2

我有一個教師模型和一個學生模型(教師has_many學生)。希望使用Filterrific通過他們的學生的名字搜索老師在Rails中使用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 
    ) 
    } 

回答

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) 
} 
+0

謝謝喬!我確實必須保留參考。另外,我不得不刪除學生。 from students.first_name,students.last_name,and students.email –

+0

我不需要包含'references'調用。 http://filterrific.clearcove.ca/pages/active_record_scope_patterns.html – eebbesen