views:

13

answers:

1

I use TS to search trough 2 models (classes) at the same time:

class Product < ActiveRecord::Base
  belongs_to :user
  belongs_to :photo
  has_many :variants
end

class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :photo
end

In controller:

@item_facets = ThinkingSphinx.facets( options[:search],
                                      :classes => [Product, Article],
                                      :include => [:user, :photo])
@items = @items_facets.for

Is it possible somehow to use eager loading for :variants?

A: 

It's a little ugly but it works:

ids = @items.select { |item| item.is_a?(Product) }.map(&:variant_id)
variants = {}
Variant.find(ids).each { |v| variants[v.id] = v }
@items.each do |item|
  item.variant = variants[item.variant_id] if item.is_a?(Product)
end

Is there a better solution?

Voldy