【问题标题】:Grouping Sunspot Models to get sorting/count on View对太阳黑子模型进行分组以对视图进行排序/计数
【发布时间】:2012-06-13 15:50:53
【问题描述】:
  @search = Sunspot.search(Event, Person, Organization) do
    keywords params[:q]
    order_by(:score)
  end

根据搜索结果,我想创建一个模型列表,其中包含每个模型的计数。

  • 事件 (12)
  • 人 (5)
  • 组织 (3)

有没有办法在 Sunspot 中进行这种类型的分组?

<% @search.each_hit_with_result do |hit, result| -%>
    <%= result.class %> <!- Gives me Model, but repeated -->
<% end %>

【问题讨论】:

    标签: ruby-on-rails sunspot-rails


    【解决方案1】:

    可能有一种更聪明的方法,但一种可能的方法是获取这样的类数组

    classes = @search.results.map(&:class) # this will give array of returned classes
    

    然后按照this link中的建议进行操作

    h = Hash.new(0)
    classes.each { | v | h.store(v, h[v]+1) }
    
    # h = { 3=>3, 2=>1, 1=>1, 4=>1 }
    

    希望对你有帮助

    【讨论】:

    • 由于 Sunspot 自动添加分页,我必须将 per_page 设置为 999999 或者您可以进行计数。
    • 是的,这似乎是唯一的方法。不过对我来说,伯爵看起来更干净。顺便说一句,只要确保您没有返回大量结果,否则随着时间的推移,这可能会减慢很多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多