用多个字段搜索时,按特定字段的最接近匹配进行Rails排序

时间:2018-08-07 08:36:50

标签: ruby-on-rails sorting search

我的网站上有搜索帖子功能。它允许用户按标题和内容搜索帖子。我想将search by title的匹配结果优先于search by content

例如:

发布

id 1
title "Sample Title"
content "Content 1"

id 2
title "Random"
content "But it contains Title here"

使用查询“标题”进行搜索时,我希望它返回两个结果,但将ID 1优先于2。

我尝试做的事情:

发布模型:

scope :search_by_title, -> (keyword) {
  return if keyword.nil?
  where('title LIKE ?', "%#{sanitize_sql_like(keyword)}%")
}
scope :search_by_content, -> (keyword) {
  return if keyword.nil?
  where('content LIKE ?', "%#{sanitize_sql_like(keyword)}%")
}

然后在我的控制器中:

 @posts_by_title = Post.search_by_name(query)
 @posts_by_content = Post.search_by_content(query)
 @posts = @posts_by_title + @posts_by_content

它可以工作,但是需要查询两次。所以我只是想知道有没有更好的方法来达到这个结果?

1 个答案:

答案 0 :(得分:0)

您可以改为以编程方式解决此问题。将控制器中的所有帖子查询到一个数组中并对其进行处理,确保仅需命中数据库即可提取所需的一切。在您的情况下,应为idtitlecontent

然后在数组中过滤掉不匹配的帖子,保留匹配的帖子并按照您的条件对其进行排序。