dmonopoly
dmonopoly

Reputation: 3331

rails with jquery token-input: first character ignored in search

UsersController's index:

@users = current_user.other_users.where("first_name like ?", "%#{params[:q]}%")

1) Search works fine in the text field except that the first character isn't detected.

Example: If I search with "J" for "John" I won't get any results, but if I do "o" I will get "John" as I should.

2) I'm wondering how you add an additional search condition above for last_name...? I thought something like

.where("first_name like ? or last_name like ?", "%#{params[:q]}%")

would work, but it doesn't...

Help appreciated!

Upvotes: 2

Views: 530

Answers (3)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

I'm betting you're using Postgres as your database, where LIKE clauses are case-sensitive. To search case-insensitive in Postgres:

.where("first_name ILIKE ? or last_name ILIKE ?", "%#{params[:q]}%")

This SO has plenty of background: How do you write a case insensitive query for both MySQL and Postgres?

Other alternatives:

Upvotes: 3

matsko
matsko

Reputation: 22203

The reason why the first letter isn't being detected is because you have a % infront of the first and last name columns within the where statement. So since there is nothing behind J then that's why %John% won't work.

You will need to look for both before and after statements.

This would work.

q1 = params[:q].to_s + '%'
q2 = '%' + q1
where(["first_name LIKE ? OR last_name LIKE ? OR first_name LIKE ? OR last_name LIKE", q1,q1,q2,q2])

Then put UNIQUE in your SQL statement to make them all unique rows.

It's better to use a fulltext search index for this kind of stuff anyway since the LIKE operations aren't indexed for front and back operations (only front). This is assuming you're using MySQL as your DB backend.

Upvotes: 0

davidrac
davidrac

Reputation: 10738

  1. I'm not sure why this does not match. Maybe you should add ' ' around the parameter: "first_name like '?'"

  2. I think you should have two params in there:

.where("first_name like ? or last_name like ?", "%#{params[:q]}%", "%#{params[:q]}%")

Upvotes: 1

Related Questions