0

I have a collection of Fabrics each Fabric has many colours.

My DB association Fabric has_many Colours through Fabric_colours

I am using solr to index my Fabrics, so structuring complex SQL queries is not possible.

The join model Fabric_colours, holds fabric_id colour_id percentage

The Colours model holds the hex value of each Colour.

I would like to display in my view,

each colour present in a said fabric, the percentage in which said Colour is present

My view is loading dozens of fabrics at a time and I do not want to perform additional queries to get this information. It was my understanding that Solr has pulled all of the associated table’s data into a single ‘document’ so this should not be necessary.

At present in my _fabric partial i have the following code showing the colours present in that fabric.

    <% fabric.colours.each do |c| %>
        <%= c.hex %>
    <% end%>

how would i call the the specific join table entry linking the fabric, and that specific colour, to extract the percentage?

RMcNairn
  • 491
  • 1
  • 5
  • 20

1 Answers1

0

Solr can store data inside its index so it won't hit the database when you want to display the data. I recommend you the sunspot gem that will you to achieve this. Checkout its wiki, especially the Setting up classes for search and indexing section where it is described.

Be aware that this way leads to data doubling - you will have the same data stored in the database and in the solr index.

Instead of storing data in solr index I advise you to use eager loading. You can preload colour percentages and also the color objects in the controller.

def show
  # Loads fabrics, the join table and colours
  @fabrics = Fabric.includes(:fabric_colours => [:colour])... # .all or .where or whatever
end

def search
  # Searches for fabrics with eager loading
  search = Fabric.search(:include => { :fabric_colours => :colour }) do
    # ... search criteria
  end
  @fabrics = search.results
end

If this is still slow for you, use caching.

DavidRH
  • 809
  • 5
  • 8