Rails gem rails3-jquery-autocomplete:如何查询多个字段 [英] Rails gem rails3-jquery-autocomplete: How do I query multiple fields

查看:20
本文介绍了Rails gem rails3-jquery-autocomplete:如何查询多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此处找到的 rails3-jquery-autocomplete gem:http://github.com/crowdint/rails3-jquery-autocomplete

I'm using the rails3-jquery-autocomplete gem found here: http://github.com/crowdint/rails3-jquery-autocomplete

关于如何查询模型的单个属性的说明很清楚,我可以毫无问题地进行这项工作.

The instructions are clear for how to query a single attribute of a model and I am able to make that work without a problem.

我的 Person 模型有两个我想要组合和查询的属性.它们是 first_namelast_name.我想将它们组合成一个名为 full_name 的伪属性.目前,我收到此错误:

My Person model has two attributes that I would like to combine and query, however. They are first_name and last_name. I would like to combine them into a pseudo-attribute called full_name. Currently, I receive this error:

ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column: full_name: SELECT     "people".* FROM       "people"  WHERE     (LOWER(full_name) LIKE 'cla%') ORDER BY  full_name ASC LIMIT 10):

Person 模型没有 full_name 属性,尽管我在 Person 模型文件中有以下方法:

There is no full_name attribute of the Person model, though I have the following method in the Person model file:

def full_name
  "#{self.first_name} #{self.last_name}"
end

如何修改 Person 模型文件,以便调用 full_name 查询数据库以匹配 first_namelast_name 的组合?

How do I modify the Person model file so that calls to full_name queries the database to match a combination of first_name and last_name?

推荐答案

您的伪属性仅适用于已检索到的记录,但与搜索记录无关.可能最简单的解决方案是一个名为 命名范围 像:

Your pseudo attribute works only on records already retrieved, but it has no bearing on searching for records. Probably the easiest solution is a named named scope like:

 scope :search_by_name, lambda { |q|
   (q ? where(["first_name LIKE ? or last_name LIKE ? or concat(first_name, ' ', last_name) like ?", '%'+ q + '%', '%'+ q + '%','%'+ q + '%' ])  : {})
 }

因此,调用如下:

Person.search_by_name(params[:q]) 

将返回适当的结果集.如果没有传递参数,它还将返回所有条目(或者更具体地说,此范围不会添加任何额外内容),使其成为索引操作的简单插入.

will return an appropriate result set. It will also return all entries if no param was passed (or more specifically, this scope will add nothing extra), making it an easy drop-in for the index action.

这篇关于Rails gem rails3-jquery-autocomplete:如何查询多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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