How to search user by name with pagination

We have frontend application that use Discourse as core and we want to implement user search with pagination.

Currently, I don’t see that this api (/search?q=name) support type_filter: user. Any idea how to implement this one?

This is a workaround that we did.

  1. open search_controller.rb and add this line.
def show
    @search_term = params.permit(:q)[:q]

    // allow type_filter from query params
    @type_filter = params.permit(:type_filter)[:type_filter] || 'topic'

   ...
  1. add offset to search.rb
  // it is around line 780
  def user_search
    return if SiteSetting.hide_user_profiles_from_public && !@guardian.user

    users = User.includes(:user_search_data)
      .references(:user_search_data)
      .where(active: true)
      .where(staged: false)
      .where("user_search_data.search_data @@ #{ts_query("simple")}")
      .order("CASE WHEN username_lower = '#{@original_term.downcase}' THEN 0 ELSE 1 END")
      .order("last_posted_at DESC")
      .offset(offset) // this line
      .limit(limit)

    users.each do |user|
      @results.add(user)
    end
  end

Then you will be able to search user with /search?q=name&type_filter=user&page=1, by default it will get 50 users and use page to get more.

Hope this help! :grin:

3 Likes

Great idea! we also work with Discourse API and when we try to use search API, we found this problem also. I can help to do this.

3 Likes