我正在尝试向用户显示当前用户关注的公司/技能/学校的其他用户。创建个人资料中具有此类属性的用户列表后,我想按与每个返回用户关联的相关公司/技能/学校的数量对其进行排序,以在列表顶部显示最相关的用户。
虽然这行得通,但它非常丑陋并且速度很慢,而且我不确定从哪里开始清理它。一些指示将不胜感激。
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
最佳答案
一些提示:
User.text_search
方法有什么作用?您使用的是全文搜索引擎吗?如果是这样,您应该构建一个搜索查询(term1 OR term2 OR term3
等),而不是对每个术语都单独搜索。在
User.text_search
方法中,您是否正在创建数据库连接以预取教育、职位、持有的技能及其公司、学校和技能名称?这将大大减少数据库查询的数量。考虑 denormalizing你的数据库架构。也许您可以将
company_name
列添加到您的positions
表,将school_name
列添加到您的educations
和一个skill_name
列到您的held_skills
表。这将大大简化您的查询并提高性能。
这些将是一些起点。
关于ruby-on-rails - 我如何加快这个丑陋的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688441/