Search code examples
ruby-on-railssphinxthinking-sphinxfaceted-search

Thinking Sphinx name of facets


I have define facets for product model like this:

product_index.erb

ThinkingSphinx::Index.define :product, :with => :active_record do  
  indexes publish
  indexes name, :sortable => true
  indexes price, :sortable => true
  indexes manufacturer.permalink, :as => :manufacturer, :facet => true
  has manufacturer_id
end

and facets in view:

<% @facets.each do |facet, facet_options| %>
<h5><%= facet %></h5>
<ul>
    <% facet_options.each do |option, count| %>
    <li><%= link_to "#{option} (#{count})",
    :params => {facet => option, :page => 1} %></li>
    <% end %>
</ul>

This is generate facets for manufacturers like this:

manufacturer

  • < a href="manufacturer=manufacturer-permalink&page=1">manufacturer-permalink (53)

How add own name for title (e.g. replace manufacturer to Brand) and add own name for link (e.g. replace manufacturer-permalink (53) to Manufacturer.name (53) (where Manufacturer is a model class))


Solution

  • I wrote something for this very purpose - to translate foreign key facets to their corresponding objects. You can find the code here: https://gist.github.com/pat/5477820

    You will need to be clear about which facets to iterate through - otherwise you'll end up with both manufacturer_id and manufacturers listed in your HTML.

    Here's what could possibly go in your controller's action, after the facet search query:

    FacetExpander.expand @facets, :manufacturer
    

    Then in your view:

    <h5>Manufacturers</h5>
    <ul>
      <% @facets[:manufacturers].each do |manufacturer, count| %>
      <li><%= link_to "#{manufacturer.name} (#{count})",
        :params => {:manufacturer_id => manufacturer.id, :page => 1} %></li>
      <% end %>
    </ul>