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')