Adear Adear - 9 days ago 6
Ruby Question

how can i order by relevance in ruby on rails

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.

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 :)

Answer

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

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