0

我有一系列面料,每种面料都有多种颜色。

我的数据库关联 Fabric has_many Colors through Fabric_colours

我正在使用 solr 来索引我的 Fabrics,因此无法构建复杂的 SQL 查询。

连接模型 Fabric_colours,保存 fabric_id colour_id 百分比

颜色模型保存每种颜色的十六进制值。

我想在我的视图中显示,

所述织物中存在的每种颜色,所述颜色存在的百分比

我的观点是一次加载几十个结构,我不想执行额外的查询来获取这些信息。据我了解,Solr 已将所有关联表的数据提取到单个“文档”中,因此没有必要这样做。

目前在我的 _fabric 部分中,我有以下代码显示该织物中存在的颜色。

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

我如何调用链接织物和特定颜色的特定连接表条目来提取百分比?

4

1 回答 1

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.

于 2012-09-23T13:09:35.330 回答