Return instances of multiple ActiveRecord models from a single search

  • Download Gist
tire-search-with-multiple-active-record-instances.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
require 'tire'
require 'yajl/json_gem'
require 'active_record'
require 'logger'
 
# === Setup ===
 
# ActiveRecord::Base.logger = Logger.new(STDERR)
# Tire.configure { logger STDERR }
 
ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => ":memory:" )
 
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define(:version => 1) do
create_table :articles do |t|
t.string :title
t.datetime :created_at, :default => 'NOW()'
end
create_table :comments do |t|
t.string :title
t.datetime :created_at, :default => 'NOW()'
end
end
 
class Article < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
 
index_name 'blog'
end
 
class Comment < ActiveRecord::Base
include Tire::Model::Search
include Tire::Model::Callbacks
 
index_name 'blog'
end
 
Article.create :title => 'Hello One'
Article.create :title => 'Hello Two'
 
Comment.create :title => 'Hello, first!'
 
Article.index.refresh
 
# === The Search Logic ===
 
s = Tire.search('blog', :fields => [:id]) { query { string 'hello' } }
 
results = s.results
ids = results.map(&:id)
 
puts "", "Got these results", '-'*80, results.to_a.inspect
 
puts "", "Got these IDs:", '-'*80, ids.inspect
 
ids_by_type = {}
 
results.each do |item|
ids_by_type[item._type] ||= []
ids_by_type[item._type] << item.id
end
 
puts "", "Got these types and IDs:", '-'*80, ids_by_type
 
records = []
 
ids_by_type.keys.each do |type|
klass = type.camelize.constantize
records << klass.find( ids_by_type[type] )
end
 
records.flatten!
 
records = results.map do |result|
records.detect do |record|
record.class.to_s.underscore == result._type && record.id.to_s == result.id.to_s
end
end
 
puts "", "Got these ActiveRecord instances:", '-'*80, records.inspect

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.