Skip to content

Instantly share code, notes, and snippets.

@danielpietzsch
Created May 24, 2011 05:53
Show Gist options
  • Save danielpietzsch/988189 to your computer and use it in GitHub Desktop.
Save danielpietzsch/988189 to your computer and use it in GitHub Desktop.
Controller index view with pagination and AJAX search
def index
@instance = Model.search(params[:search], :include => :associated_model).paginate(:page => params[:page])
respond_to do |format|
format.html
format.js
end
end
<div class="searchbox">
<label for="search">Search:</label><input id="search" type="search" name="search" placeholder="attr1, attr2 or attr3" value="<%= params[:search] %>"/>
<%= observe_field :search, :url => { :action => :index }, :frequency => 2, :with => "search", :method => "get" %>
</div>
<%= render :partial => 'list_partial' %>
page.replace_html :id_of_element_to_replace, :partial => "list_partial"
def self.search(search, options = {})
if search
words = search.gsub('%', '\\\\\%').split
search_string = words.collect { |word| "(attr1 ILIKE '%#{word}%' OR attr2 ILIKE '%#{word}%' OR attr3 ILIKE '%#{word}%')" }.join " AND "
all(options.merge({ :conditions => sanitize_sql_for_conditions(search_string) }))
else
all(options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment