Ruby on rails 如果我尝试使用活动记录,为什么结果会变得多余?
我想在Ruby on rails 如果我尝试使用活动记录,为什么结果会变得多余?,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,我想在社区主题.title或社区主题.body或注释.body中检索包含搜索关键字的所有社区主题 但下面的代码检索并显示了一堆加倍、三倍或更多!记录:( 我只想要一张唱片,我怎么能 @community_topics = CommunityTopic.joins(:community, :comment_threads).merge(Community.not_deleted).where('community_topics.title like ? OR community_topics.bo
社区主题.title
或社区主题.body
或注释.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)
我会用一些东西,比如:
@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)
但是,查询过于复杂。为什么要合并社区。未删除?为什么要传入页面和per
?这是在控制器中实现的吗?如果是,提取到模型中。创建相关的作用域和方法。下面是一个示例(未测试):
模型
控制器
这只是一个粗略的例子。如果你能解释为什么要使用Community.not_deleted
merge,可能会将其清理干净。你能用上面生成的实际sql查询添加详细信息吗?你可以在之前的查询结束时使用uniq
方法pagination@AmitThawait如何将其添加到我的代码中?@comcommunity_topics=community_topic.join(:community,:comment_threads)。merge(community.not_deleted)。where('community_topics.title like?或community_topics.body like?或comments.body like?),“%”“%“+params[:search]+”,“%“+”,“%”+params[:search]+”,“%”+““%”+params[:search]+”)。order('last(search]+“%”)。order('last(在DESC处的最后一次活动
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)