July 14, 2009

How to add a feature to spotlight a column search on ActiveScaffold

ActiveScaffold is really nice to build something with Ruby on Rails. that saves my time a lot. though it may requires extra internal knowledges to do something that it doesn't provide. even generally.

So this is just a tips to add a column-based search feature to the ActiveScaffold. you can just patch it out to lib/active_scaffold/actions/search.rb and/or live_search.rb, or add it to your controller where you want to enable this feature.


def do_search
@query = params[:search].to_s.strip rescue ''

unless @query.empty?
tmpq = @query.split(' ')
columns_query = {}
tmpq.delete_if do |x|
retval = false
if x =~ /\A(.*):(.*)\Z/ then
p = $1
v = $2
if !p.nil? && !p.empty? && !v.nil? && !v.empty? &&
active_scaffold_config.columns.include?(p)
then
columns_query[p] = v
retval = true
end
end
retval
end
columns = active_scaffold_config.live_search.columns
like_pattern = active_scaffold_config.live_search.full_text_search? ? '%?%' : '?%'
search_conditions = self.class.create_conditions_for_columns(tmpq, columns, like_pattern)
self.active_scaffold_conditions = merge_conditions(self.active_scaffold_conditions, search_conditions)
columns_query.each do |p,v|
active_scaffold_config.columns.each do |column|
next if column.column.nil?
if column.column.name == p then
sql = column.column.text? ? "LOWER(#{column.search_sql}) LIKE ?" : "#{column.search_sql} = ?"
token = column.column.text? ? like_pattern.sub('?', v.downcase) : column.column.type_cast(v)
self.active_scaffold_conditions = merge_conditions(self.active_scaffold_conditions, [sql, token])
break
end
end
end
@filtered = !search_conditions.blank?

includes_for_search_columns = columns.collect{ |column| column.includes}.flatten.uniq.compact
self.active_scaffold_joins.concat includes_for_search_columns

active_scaffold_config.list.user.page = nil
end
end

No comments: