2011-04-09 24 views
2

我想根据字母列表列出用户...即,当我点击字母“A”时,它应该列出以字母A开头的所有用户,以B开头的所有用户, C等Rails - 根据首字母搜索和排序

对于此我使用的代码

@users = User.search(params[:char]) 

params[:char]我传递字母(A,b,C,d等)。

此代码搜索包含此字母的单词。

取而代之,我想要一个以关键字开头的用户列表。

请你可以建议如何去与此。

谢谢。

回答

3

您可能想要使用SQL查询。

@users = User.all(:conditions => "name like '#{params[:char]}%'") 

查看ActiveRecord Finder MethodsMySQL Pattern Matching文档的详细信息。 (即使你使用的是不同的数据库,查询应该是非常相似的。)

+0

很多很多的感谢... – lamrin 2011-04-09 05:42:54

+0

您可能希望将一些不区分大小写的调整增加那。 – 2011-04-09 05:44:11

+0

我还会添加一个索引:'create index name_first_letter_idx on user(name(1))' – Wes 2011-04-09 05:59:38

0
@user = User.all :conditions => ['substr(name,1,1) = ?', selected_letter] 
+1

但它会比较字母值,对吗?所以它只会搜索不是大写字母的小写字母 – chaitanya 2012-08-16 10:02:25

2

对于想你可以这样做的第一个字母来搜索人:

Patient.where('substr(name, 1, 1) = ?', 'm') 

修正:我刚才读了区分大小写的评论,所以你可以包含任何字母的情况下,敏感:

Patient.where('substr(field_name, 1, 1) = ? OR substr(field_name, 1, 1) = ?', 'C', 'c') 
# there from your controller or model can replace that with 
Patient.where('substr(name, 1, 1) = ? OR substr(name, 1, 1) = ?', letter.upcase, letter.downcase) 

就是这样

0

没有足够的信誉发表评论,所以要扩大heriberto perez的回答,您可以用户lower大小写敏感的搜索

Patient.where('substr(lower(name, 1, 1)) = ?', letter.downcase)