我想在community_topics
或search keyword
或community_topics.title
community_topics.body
的所有comments.body
但下面这段代码检索并显示一堆加倍,三倍或更多!记录:( 我只希望他们作为单一记录。我怎么能?
@community_topics = CommunityTopic.joins(:community, :comment_threads).merge(Community.not_deleted).where('community_topics.title like ? OR community_topics.body like ? OR comments.body like ?', "%"+params[:search]+"%", "%"+params[:search]+"%", "%"+params[:search]+"%").order('last_active_at DESC').page(params[:page]).per(10)
答案 0 :(得分:1)
我会使用以下内容:
@community_topics = CommunityTopic.joins(:community, :comment_threads)
.merge(Community.not_deleted)
.where('community_topics.title like :term
OR community_topics.body like :term
OR comments.body like :term',
term: "%#{params[:search]}%")
.order('last_active_at DESC')
.uniq.page(params[:page]).per(10)
但是,查询过于复杂。为什么Community.not_deleted
被合并?你为什么要传递page
和per
?这是在控制器中实现的吗?如果是这样,请提取到您的模型中。创建相关的范围和方法。这是一个例子(未经测试):
model CommunityTopic
scope :latest_active, order('last_active_at DESC')
scope :eager, joins(:community, :comment_threads).merge(Community.not_deleted)
def self.search(term)
eager.where('community_topics.title like :term
OR community_topics.body like :term
OR comments.body like :term',
term: "%#{term}%").uniq
end
end
@community_topics = CommunityTopic.latest_active.search(params[:search]).page(params[:page]).per(10)
这只是一个粗略的例子。如果您可以解释为什么使用Community.not_deleted
合并,可能会清理它。你能用上面产生的实际sql查询添加细节吗?