我正在尝试向用户展示在其个人资料上拥有当前用户正在关注的公司/技能/学校的其他用户。创建个人资料中具有此类属性的用户列表后,我想按与每个返回用户关联的相关公司/技能/学校的数量对其进行排序,以在列表顶部显示最相关的用户。
虽然这行得通,但它非常丑陋并且可以预见的缓慢,我不知道从哪里开始清理它。一些指针将不胜感激。
def term_helper(terms,user)
relevant_terms = []
terms.each do |term|
if user.positions.any? { |w| w.company.downcase.include?(term.downcase) rescue nil || w.industry.downcase.include?(term.downcase) rescue nil }
relevant_terms << term
end
if user.educations.any? { |w| w.school.downcase.include?(term.downcase) rescue nil }
relevant_terms << term
end
if user.held_skills.any? { |w| w.name.downcase.include?(term.downcase) rescue nil }
relevant_terms << term
end
end
relevant_terms
end
def search
if current_user
followed_companies = current_user.followed_companies.pluck(:name)
followed_skills = current_user.followed_skills.pluck(:name)
@terms = (followed_companies + followed_skills).uniq
full_list = []
full_list_with_terms = {}
users = []
@terms.each do |term|
full_list += User.text_search(term).uniq
# using pg_search gem here
end
full_list.each_with_index do |user,index|
terms = term_helper(@terms,user)
full_list_with_terms[index] = {"user" => user, "term_count" => terms.count}
end
full_list_with_terms = full_list_with_terms.sort_by {|el| el[1]["term_count"]}
full_list_with_terms.each do |el|
users << el[1]["user"]
end
@matches = users.uniq.reverse.paginate(:page => params[:page], :per_page => 10)
end
end