Collin
Collin

Reputation: 497

Search Users with Ruby Variable as Query

I'm trying to make a simple search functionality within my app. To do this, the user will search on the page "/search/users/[query]". The parameters are setup correctly, but I cannot figure how to make it so that it searches the database for all users that the search term is in their username. I feel like I'm almost there, but it does not work:

   def search_handler
        @query = params[:query]
        @type = params[:type]
        if @type == "users"
          @users = User.all.username.match(@query/i)
        end
    end

Upvotes: 0

Views: 92

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33491

You can try passing the params[:query] to a LIKE SQL query within a where ActiveRecord statement:

def search_handler
  @query = params[:query]
  @type  = params[:type]
  if @type == 'users'
    @users = User.where('username LIKE ?', "%#{@query}%")
  end
end

That will give you all the users where the username matches with the value of @query you've passed, producing an SQL query like:

SELECT  "users".* FROM "users" WHERE (username LIKE '%blablabla%') LIMIT ?  [["LIMIT", 11]]

You could take a look to the ActiveRecord Query Methods for improving your queries in Rails.

Upvotes: 2

Related Questions