问题 在列中搜索部分字符串的活动记录


在返回产品搜索结果后,我需要在单个模型期刊上执行搜索。

有没有办法只使用完整字符串的一部分来搜索期刊标题?

def index
    @product_results = Gemgento::Search.products(params[:query])
    @editorial_results = Journal.where("headline LIKE ?", "#{params[:query]}")   
end

例如。说我的上一个日记对象有标题:“堆栈溢出博客帖子” 如果我查询活动记录:

@editorial_results = Journal.where("headline LIKE ?", "stack overflow")

就像我现在一样,它仍然需要在字符串上直接匹配。

搜索 http://guides.rubyonrails.org/active_record_querying.html 尽管有sql注入警告,但这似乎是正确的方法。

有没有办法构建搜索,以便它将返回最后一个条目? (不使用搜索库?)


916
2018-04-16 16:34


起源

试试吧 where("headline LIKE ?", "%stack overflow%") - Nitin Jain
什么是Gemgento? - C.J. Bordeleau


答案:


您在搜索字词之前和之后缺少通配符'%'。

def index
   @product_results = Gemgento::Search.products(params[:query])
   @editorial_results = Journal.where("headline LIKE ?", "%#{params[:query]}%")   
end

这意味着查询参数之前和之后都可以有任何内容。


10
2018-04-16 16:42





你需要添加 % 登录到您的SQL查询

def index
    @product_results = Gemgento::Search.products(params[:query])
    @editorial_results = Journal.
      where("headline LIKE :query", { query: "%#{params[:query]}%"})   
end

2
2018-04-16 16:43





你可以实现这一目标 Journal.where("headline LIKE ?", "%#{params[:query]}%")


1
2018-04-16 16:43