【问题标题】:Tire - sort by number of related object轮胎 - 按相关对象的数量排序
【发布时间】:2013-07-16 09:26:19
【问题描述】:

我的模型中有这样的东西:

class User < ActiveRecord::Model

  has_many :followers, :through => :as_followed_followings, :class_name => "User", :foreign_key => "follower_id", :uniq => true

  ...

  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: params[:per]) do
    end
  end

end

我希望返回按用户拥有的关注者数量排序的用户数组。

那么定义映射和索引以搜索具有计数属性的嵌套对象的正确方法是什么?

感谢阅读。

【问题讨论】:

    标签: ruby-on-rails elasticsearch tire


    【解决方案1】:

    我已通过在users 表上创建另一个字段并索引该值而不是在运行时执行嵌套搜索来解决此问题。

    这可能不是最好的解决方案,但我有最后期限。欢迎任何更好的解决方案:)

    【讨论】:

      【解决方案2】:

      尝试...

      AsFollowedFollowing.count(:group => :follower_id, :order => "count_all DESC")
      

      这是包含user_id =&gt; count的有序哈希

      如果你想循环这个哈希,试试下面

      # in controller
      @counts = AsFollowedFollowing.count(:group => :follower_id, :order => "count_all DESC")
      @users = User.where(:id => @counts.map{|k,_| k})
      
      #in view
      <% @counts.each do |k, v| %>
        <% user = @users.find{|u| u.id == k} %>
        <div><%= user.name %> | <%= v %></div>
      <% end %>
      

      【讨论】:

      • count 来自 elasticsearch 的 DSL 吗?
      • 对不起,其实我不知道elasticsearch。 count 是 ActiveRecord::Model 的方法。
      • 感谢您的回答,但由于我的问题是关于弹性搜索和轮胎宝石的,所以这不是主题:)
      猜你喜欢
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      相关资源
      最近更新 更多