TheExit
TheExit

Reputation: 5320

Condition query with LIKE does not match an exact match

I'm using the following query to search for users:

  @users = User.find( :all,
                      :select => 'users.*',
                      :conditions => ["lower(fname) || ' ' || lower(lname) LIKE ?", '%'+"#{params[:q].downcase}"+'%'],
  )

This works great for examples like so:

Bob S find Bob Smith
Bob finds Bob Smith

Problem is

Bob Smith does not find Bob Smith

How can I get the query above to return an exact match? Thanks

Upvotes: 0

Views: 977

Answers (1)

Jan Minárik
Jan Minárik

Reputation: 3267

The query is just plain wrong. First, '||' is not a concatenation operator. Second, the operator precedence makes it evaluated as:

(lower(fname)) || (' ') || (lower(lname) LIKE '%Bob Smith%')

which is not what you want. I guess you would like it:

concat(lower(fname), ' ', lower(lname)) LIKE '%Bob Smith%'

EDIT: So you can use:

@users = User.find( :all,
                  :select => 'users.*',
                  :conditions => ["concat(lower(fname), ' ', lower(lname)) LIKE ?", "%#{params[:q].downcase}%"])

EDIT2: The above is wrong, I haven't noticed it was about Postgresql. There is a '||' concatenation operator in Postgres of course. I'm not deleting this post because of the comments below but don't use it please.

Upvotes: 2

Related Questions