ruby-on-railsactiverecordarel

How to do a LIKE query in Arel and Rails?


I want to do something like:

SELECT * FROM USER WHERE NAME LIKE '%Smith%';

My attempt in Arel:

# params[:query] = 'Smith'
User.where("name like '%?%'", params[:query]).to_sql

However, this becomes:

SELECT * FROM USER WHERE NAME LIKE '%'Smith'%';

Arel wraps the query string 'Smith' correctly, but because this is a LIKE statement it doesnt work.

How does one do a LIKE query in Arel?

P.S. Bonus--I am actually trying to scan two fields on the table, both name and description, to see if there are any matches to the query. How would that work?


Solution

  • This is how you perform a like query in arel:

    users = User.arel_table
    User.where(users[:name].matches("%#{sanitize_sql_like(user_name)}%"))
    

    PS:

    users = User.arel_table
    query_string = "%#{params[query]}%"
    param_matches_string =  ->(param){ 
      users[param].matches(query_string) 
    } 
    User.where(param_matches_string.(:name)\
                           .or(param_matches_string.(:description)))