我的网站上有一个搜索帖子的功能。它允许用户按标题搜索帖子;所容纳之物我想将search by title
的匹配结果优先于search by content
。
例如:
后
id 1
title "Sample Title"
content "Content 1"
id 2
title "Random"
content "But it contains Title here"
当使用查询"Title"进行搜索时,我希望它同时返回两个结果,但将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
它可以工作,但需要进行2次查询。所以我只是想知道有没有更好的方法来实现这个结果?
您可以通过编程方式解决此问题。将控制器中的所有帖子查询到一个数组中并进行处理,确保只命中一次数据库即可获取所需的所有内容。在您的情况下应该是id
、title
和content
。
然后在数组中筛选出不匹配的帖子,保留匹配的帖子并根据您的标准进行排序。