# 如何按名称搜索用户并进行分页

**URL:** <https://meta.discourse.org/t/how-to-search-user-by-name-with-pagination/163325>\
**Category:** Feature\
**Created:** [2020年九月8日 08:40 UTC](https://meta.discourse.org/t/how-to-search-user-by-name-with-pagination/163325 "2020-09-08T08:40:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![siriwatknp](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/siriwatknp/32/189740_2.png) [@siriwatknp](https://meta.discourse.org/u/siriwatknp)\
**Post date:** [2020年九月8日 08:40 UTC](https://meta.discourse.org/t/how-to-search-user-by-name-with-pagination/163325/1 "2020-09-08T08:40:00Z")

</div>

我们有一个以前端应用为核心使用 Discourse 的项目，现在想要实现带有分页的用户搜索功能。

目前，我没有看到该 API（`/search?q=name`）支持 `type_filter: user`。请问有什么建议可以实现这一功能吗？

---

<div class="post-metadata">

**Author:** ![siriwatknp](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/siriwatknp/32/189740_2.png) [@siriwatknp](https://meta.discourse.org/u/siriwatknp)\
**Post date:** [2020年九月9日 02:36 UTC](https://meta.discourse.org/t/how-to-search-user-by-name-with-pagination/163325/2 "2020-09-09T02:36:49Z")

</div>

这是我们采用的一个临时解决方案。

1. 打开 `search_controller.rb` 并添加以下代码行。

```plaintext
def show
    @search_term = params.permit(:q)[:q]

    // 允许从查询参数中获取 type_filter
    @type_filter = params.permit(:type_filter)[:type_filter] || 'topic'

   ...

```

1. 在 `search.rb` 中添加 `offset`。

```plaintext
  // 大约在 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) // 这一行
      .limit(limit)

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

```

之后，你就可以通过 `/search?q=name&type_filter=user&page=1` 搜索用户了。默认情况下，每次会获取 50 个用户，并使用 `page` 参数来获取更多内容。

希望这能帮到你！😁

---

<div class="post-metadata">

**Author:** ![heyfirst](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/heyfirst/32/193248_2.png) [@heyfirst](https://meta.discourse.org/u/heyfirst)\
**Post date:** [2020年九月10日 04:00 UTC](https://meta.discourse.org/t/how-to-search-user-by-name-with-pagination/163325/3 "2020-09-10T04:00:40Z")

</div>

好主意！我们也使用 Discourse API，当我们尝试使用搜索 API 时，也遇到了这个问题。我可以帮忙解决。
