Rails 3 - 使用 LIKE 搜索合并的 2 列 [英] Rails 3 - Using LIKE to search a combined 2 columns

查看:45
本文介绍了Rails 3 - 使用 LIKE 搜索合并的 2 列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 ryan 的简单搜索表单教程:http://railscasts.com/episodes/37-simple-search-form

I'm following ryan's Simple Search Form tutorial here: http://railscasts.com/episodes/37-simple-search-form

我的用户模型中有以下行:

I have the following line in my Users Model:

find(:all, :conditions => ['fname LIKE ?', "%#{search}%"])

但我想做的是在组合 2 列中搜索:fname &名字

But what I'd like to do is search across a combine 2 columns,: fname & lname

当用户搜索我的全名时:

As users are searching my full names:

例如,詹姆斯布朗fname = 詹姆斯lname = 棕色

Example, James Brown fname = James lname = Brown

有没有一种方法可以在 Rails 中安全地执行此操作,并且可以跨 SQLite、MySQL 或 Postgres(heroku 使用)等数据库运行?

Is there a way to do this in Rails safely that will work across DBs like SQLite, MySQL or Postgres (heroku uses)?

谢谢!

推荐答案

它可能不漂亮,但我在我的 Person 模型中使用它:

It may not be pretty, but I use this in my Person model:

scope :by_full_name lambda {|q| 
    where("first_name LIKE ? or last_name LIKE ? or concat(last_name, ', ', first_name) LIKE ?", "%#{q}%", "%#{q}%" , "%#{q}%")
}

见我的一个 其他帖子 一些额外的内容,这将使搜索查询成为可选.

See one of my other posts for an bit extra that will let the search query be optional.

这篇关于Rails 3 - 使用 LIKE 搜索合并的 2 列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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