Rails的宝石rails3-的jQuery自动完成:如何查询多个字段 [英] Rails gem rails3-jquery-autocomplete: How do I query multiple fields
问题描述
我使用了 rails3-的jQuery自动完成
的宝石在这里找到:<一href="http://github.com/crowdint/rails3-jquery-autocomplete">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.
我的人
模型,我想不过结合和查询,两个属性。他们是 FIRST_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):
还有就是人物模型没有 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
我如何修改人物模型文件,以便调用 FULL_NAME
查询数据库,以匹配 FIRST_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
?
推荐答案
您的伪属性仅适用于已检索到的记录,但对搜索结果没有影响。也许最简单的解决方案是一个名为<一个href="http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/">named范围喜欢的:
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 + '%' ]) : {})
}
因此,像通话:
Thus, a call like:
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的宝石rails3-的jQuery自动完成:如何查询多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!