lamrin
lamrin

Reputation: 1441

Rails - search and sort based on first letter

I wanted to list users based on alphabets listing... i.e when I click on letter "A" it should list all the users starting with letter A, same case for B, C, etc.

For this I am using the code

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

in params[:char] I am passing letters (a, b, c, d, etc.).

This code searches for a word with this letter.

Instead I want a list of users starting with perticular letter.

Please can you suggest how to go with this.

Thanks.

Upvotes: 2

Views: 4628

Answers (3)

Heriberto Magaña
Heriberto Magaña

Reputation: 898

For the people that want to search by the first letter you can do something like:

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

Correction: I just read the comment for case sensitive so you can include any of the letters case sensitive with:

 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)

That's it

Upvotes: 3

Wes
Wes

Reputation: 6585

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

Upvotes: 0

Austin Taylor
Austin Taylor

Reputation: 5477

You probably want to use a SQL like query.

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

See the documentation on ActiveRecord Finder Methods and MySQL Pattern Matching for more information. (Even if you are using a different database, the query should be pretty similar.)

Upvotes: 4

Related Questions