Created
October 25, 2011 14:50
-
-
Save karmi/1312996 to your computer and use it in GitHub Desktop.
Return instances of multiple ActiveRecord models from a single search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment