# 根据自定义字段检索主题？

**URL:** https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879
**Category:** Development
**Created:** [2021年八月9日 21:39 UTC](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879 "2021-08-09T21:39:27Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![JQ331](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@JQ331](https://meta.discourse.org/u/JQ331)
#### Post date: [2021年八月11日 12:55 UTC](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879/4 "2021-08-11T12:55:07Z")

</div>

编辑：在深入研究 `api.addDiscoveryQueryParam` 后，我现在大概明白了：

我想以编程方式检索所有自定义字段为 `fun_level = super-duper-fun` 的主题。我认为也许可以通过一个控制器方法来实现？（[仍在摸索中](https://meta.discourse.org/t/error-pg-undefinedcolumn-custom-field-not-creating-column/200115/3)）。

另一种方法是使用 `ajax("/search")` 进行搜索，即基于自定义字段 `fun_level=super-duper-fun` 搜索所有主题。但仅创建自定义字段还不足以启用此功能。我需要将自定义字段 `fun_level` 设置为可搜索的字段之一（就像可以搜索特定分类、标签等一样），而这并不是自动完成的。

在某种程度上，需要在 JS 文件中使用 `api.addDiscoveryQueryParam`，并结合 `plugin.rb` 中的 `TopicQuery` 才能实现这一点。但说实话，我还没能让它正常工作。我见过一些插件使用了这些方法，但我还没能弄清楚它们是如何“搞定”的。我认为还需要一些额外的代码，但我还没找到。

如何从这些方法过渡到实际上让自定义字段可作为搜索项使用？

> **较早的回复**
>
> 谢谢，@angus。需要澄清的是，目标并非让用户在搜索框中手动输入搜索值。目标是基于某个自定义字段以编程方式检索主题。例如，用户访问页面 `/fun_levels/super-duper-fun` 时，应加载所有字段 `fun_level` = ‘super-duper-fun’ 的主题。
> 
> `api.addDiscoveryQueryParam` 是用于这个目的吗？
> 
> 查看类似 [这里](https://github.com/discourse/discourse-solved/blob/f5c5f28ef04fa713dd7a63f81f60afcd6932ea9c/assets/javascripts/discourse/initializers/extend-for-solved-button.js.es6) 的示例，我不确定 `addDiscoveryQueryParam` 是如何实际检索主题的（我认为调用该方法并不会返回我可以解析的结果）。
> 
> 也许它是为了允许用户在搜索框中手动按该术语搜索？这不是我想要的情况。（我可能确实漏掉了什么）。
> 
> 我之前提到使用 `ajax("/search...")`，因为这是我目前能想到的返回主题的最佳方式，但我想知道是否有更高效的方法，甚至包括设置模型和控制器方法来自动显示主题，就像 `tags/:tag-name` 那样（那更复杂，所以我希望能避免，但如果这是最好的方法，我会考虑）。

---

_[View the full topic](https://meta.discourse.org/t/retrieve-topics-based-on-custom-field/199879)._
