Skip to content

Instantly share code, notes, and snippets.

@ecin
Created October 28, 2010 14:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ecin/651479 to your computer and use it in GitHub Desktop.
Save ecin/651479 to your computer and use it in GitHub Desktop.
Search model for system-wide searching with Texticle.
class Search < ActiveRecord::Base
# We want to reference various models
belongs_to :searchable, :polymorphic => true
# Wish we could eliminate n + 1 query problems,
# but we can't include polymorphic models when
# using scopes to search in Rails 3
# default_scope :include => :searchable
# Search.new('query') to search for 'query'
# across searchable models
def self.new(query)
query = query.to_s
return [] if query.empty?
self.search(query).map!(&:searchable)
end
# Search records are never modified
def readonly?; true; end
# Our view doesn't have primary keys, so we need
# to be explicit about how to tell different search
# results apart; without this, we can't use :include
# to avoid n + 1 query problems
def hash; [searchable_id, searchable_type].hash; end
def eql?(result)
searchable_id == result.searchable_id and
searchable_type == result.searchable_type
end
end
@monfresh
Copy link

monfresh commented May 2, 2014

To reduce SQL queries and to avoid duplicate results, change line 15 to this:

self.search(query).preload(:searchable).map!(&:searchable).uniq

@gustavoelizalde
Copy link

I'm getting

undefined method map!' for #Search::ActiveRecord_Relation:0x00007efd95f1bed8`

Working on Rails 5... @monfresh do you have any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment