我如何通过ruby on rails的相关性排序?

时间:2023-01-12 20:14:46

i have a query happening

我有一个查询

contractors = User.all

@tools = Tool.all

tools_list = []

    @tools.each do |t|
        if params[t.name]
            tools_list.push("#{t.name}")
        end
    end

contractors = contractors.joins(:tools).where('tools.name IN (?) ', tools_list).uniq

so this looks through my params and then if a tool in the list is found it adds it to an array and then searches for all people that have at least one of these tools in there tools set.

这是通过我的params,如果列表中的工具被发现它将它添加到一个数组中然后搜索所有在工具集中至少有一个工具的人。

my question is how do i then order my results so that the people with all of the tools specified come out at the top of the list and then people with less come below?

我的问题是,我怎样才能命令我的结果,让那些拥有所有工具的人排在名单的最前面,然后下面的人就少了?

so to clarify at the moment i get a list in no particular order of all of my contractors that have at least one of the tools specified. how do i order that list so that people with more of the tools appear on the top of the list and people with less appear on the bottom?

因此,现在要澄清的是,我得到了一个列表,并不是所有的承包商都有至少一个指定的工具。我如何对列表进行排序,使拥有更多工具的人出现在列表的顶部,而拥有较少工具的人出现在底部?

Thank you in advance with any help :)

提前感谢您的帮助:)

1 个解决方案

#1


3  

you can try this, most of SQL clauses (if not all of them) are defined in ActiveRecord:

您可以尝试一下,大部分SQL子句(如果不是全部的话)都是在ActiveRecord中定义的:

User
  .joins(:tools)
  .select('users.*, count(tools.id) "counting"')
  .where(tools: { name: tools_list })
  .having('counting > 0')
  .group('users.id')
  .order('counting DESC')

#1


3  

you can try this, most of SQL clauses (if not all of them) are defined in ActiveRecord:

您可以尝试一下,大部分SQL子句(如果不是全部的话)都是在ActiveRecord中定义的:

User
  .joins(:tools)
  .select('users.*, count(tools.id) "counting"')
  .where(tools: { name: tools_list })
  .having('counting > 0')
  .group('users.id')
  .order('counting DESC')