@@ -102,11 +102,26 @@ def build_conditions_for(query)
102102 criteria
103103 end
104104
105- def search_condition ( column , value )
106- model , column = column . split ( '.' )
107- model = model . singularize . titleize . gsub ( '/' , '::' ) . gsub ( / / , '' ) . constantize
105+ # Allow searchable columns to be passed in as an array of models.
106+ # Format: [model, model, model.field]
107+ # This allows searching on nested models/tables where active record aliases table names
108+ # Examples:
109+ # Model1.joins(:employees, {:model2 => :employees})
110+ # @searchable_columns << ['model2', 'employee.first_name']
111+ def search_condition ( columns , value )
112+ if columns . is_a? ( Array )
113+ models = columns . map { |c | c . split ( '.' ) . first }
114+ column_name = columns . find { |c | c =~ /\. / } . split ( '.' ) . last
115+ models . sort! # assume that the tables in the active record auto-generated table alias are combined alphabetically
116+ table_alias = models . map { |m | m . downcase . pluralize . gsub ( /\W +/ , '_' ) } . join ( '_' )
117+ primary_table = models [ 0 ] . singularize . titleize . gsub ( /\W +/ , '_' ) . constantize
118+ table = primary_table . arel_table . alias table_alias
119+ else
120+ model , column_name = columns . split ( '.' )
121+ table = model . singularize . titleize . gsub ( '/' , '::' ) . gsub ( / / , '' ) . constantize . arel_table
122+ end
108123
109- casted_column = ::Arel ::Nodes ::NamedFunction . new ( 'CAST' , [ model . arel_table [ column . to_sym ] . as ( typecast ) ] )
124+ casted_column = ::Arel ::Nodes ::NamedFunction . new ( 'CAST' , [ table [ column_name . to_sym ] . as ( typecast ) ] )
110125 casted_column . matches ( "%#{ value } %" )
111126 end
112127
0 commit comments