在 Rails 3.0 中搜索多个数据库列 [英] Search multiple db columns in Rails 3.0

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

问题描述

我正在尝试编写一个语句来搜索 2 个 db 列并返回结果.如果不使用像 Searchlogic 这样的 gem,这是否可以轻松完成?

I'm trying to write a statement that searches 2 db columns and returns results. Can this be done easily without the use of a gem like Searchlogic?

def self.search(search)
  if search
    find(:all, :conditions => ['city LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end

到目前为止,我所拥有的是对我的数据库的城市字段执行搜索的语句.但是,我想包含一些功能来涵盖某人按州搜索的情况.

What I have so far is a statement that performs a search on the city field of my database. However, I'd like to include functionality to cover the case of someone searching by state.

因此,如果有人输入CA",搜索将返回加利福尼亚州的所有列表.如果用户键入洛杉矶",将返回洛杉矶的列表.简而言之,我想同时查询 2 个 db 字段并返回适当的结果.这可以用简单的语句完成吗?

So if someone types 'CA' the search will return every listing in California. If the user types 'Los Angeles' the listing in Los Angeles will be returned. So in short, I'd like to query 2 db fields at the same time and return appropriate results. Can this be done with a simple statement?

推荐答案

最好的办法是实现像 solr 或 sphinx 这样的全文解决方案.或者,如果您现在想让事情尽可能简单,您只需 OR 搜索:

The best thing to do would be to implement a fulltext solution like solr or sphinx. Alternatively, if you want to keep things as simple as possible for now, you would just OR the search:

def self.search(search)
  if search
    find(:all, :conditions => ['city LIKE ? OR state LIKE ?', ["%#{search}%"]*2].flatten)
  else
    find(:all)
  end
end

更新:语法替代(更好)通过 Jeffrey W.

UPDATE: syntax alternative (better) via Jeffrey W.

find(:all, :conditions => ['city LIKE :search OR state LIKE :search', {:search => "%#{search}%"}])

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

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