Ruby on Rails的 - 在数据库中搜索基于查询 [英] Ruby on Rails - search in database based on a query

查看:100
本文介绍了Ruby on Rails的 - 在数据库中搜索基于查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表格,在这里我设置了,我想浏览查询,例如松下VIERA 。 这就是我如何搜索数据库术语:

I have a simple form, where I set up a query that I want to browse, for example panasonic viera. This is on how I search the term in database:

Product.where("name ilike ?", "%#{params[:q]}%").order('price')

查询看起来像%的Panasonic VIERA%,但我会需要搜索查询是这样的:%松下%VIERA% - 我需要找到所有产品,哪里是在标题中注明的松下 VIERA ...但如何让这个查询?

The query looks like %panasonic viera%, but I would need to search the query this way: %panasonic%viera% - I need to find all products, where is in the title the word panasonic or viera... but how to make this query?

推荐答案

一个解决办法是要分手查询到个别条款,并建立了一套由连接数据库查询

One solution would be to break up your query into individual terms and build a set of database queries connected by OR.

terms = params[:q].split
query = terms.map { |term| "name like '%#{term}%'" }.join(" OR ")
Product.where(query).order('price')

这篇关于Ruby on Rails的 - 在数据库中搜索基于查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆