# 如何向根路径添加路由

**URL:** https://meta.discourse.org/t/how-to-add-route-to-root-path/186141
**Category:** Development
**Created:** [2021年四月8日 20:51 UTC](https://meta.discourse.org/t/how-to-add-route-to-root-path/186141 "2021-04-08T20:51:31Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [2021年四月8日 20:51 UTC](https://meta.discourse.org/t/how-to-add-route-to-root-path/186141/1 "2021-04-08T20:51:31Z")

</div>

在我的插件中，`config/routes.rb` 里有如下路由：

```plaintext
Pfaffmanager::Engine.routes.draw do
  get "/ssh-key/:hostname" => "serverkeys#get_pub_key_by_hostname", constraints: { end

```

我可以执行：

```
  curl https://www.pfaffmanager.com/pfaffmanager/ssh-key/test.myforum.us

```

并按预期获取公钥。🎉

但我不想就此止步（而且用户几乎肯定会复制粘贴这个请求，所以多 9 个字符无所谓），我希望能够执行：

```
  curl https://www.pfaffmanager.com/ssh-key/test.myforum.us

```

我查看了许多其他插件，感觉类似下面的写法应该可以生效：

```plaintext
Discourse::Application.routes.prepend do
  get "/ssh-key/:hostname" => "serverkeys#get_pub_key_by_hostname", constraints: { hostname: /[^\/]+/ }
end

```

但这完全不起作用。我尝试过一些方法（其实尝试了很多，本不该在这件事上浪费时间），有些看起来似乎能正确匹配路由，但随后我还需要做……一些……操作，来告诉它去 `pfaffmanager` 中查找 `get_pub_key_by_name` 控制器。

---

<div class="post-metadata">

### Author: ![Falco](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/falco/32/179432_2.png) [@Falco](https://meta.discourse.org/u/Falco)
#### Post date: [2021年四月8日 21:00 UTC](https://meta.discourse.org/t/how-to-add-route-to-root-path/186141/2 "2021-04-08T21:00:10Z")

</div>

你试过按照这个链接操作，并相应地修改 `at:` 参数吗？

> <https://github.com/discourse/discourse/blob/main/plugins/discourse-narrative-bot/plugin.rb#L125-L131>

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [2021年四月8日 21:34 UTC](https://meta.discourse.org/t/how-to-add-route-to-root-path/186141/3 "2021-04-08T21:34:51Z")

</div>

谢谢，Rafael！这帮我解决了问题。

基本上，我只是将插件挂载到 `/`，然后在 `....routes.draw` 中为路由添加了 `/pfaffmanager` 前缀。和大多数这类问题一样，一旦找到答案，就会发现其实显而易见。

---

<div class="post-metadata">

### Author: ![riking](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/riking/32/170938_2.png) [@riking](https://meta.discourse.org/u/riking)
#### Post date: [2021年四月8日 22:42 UTC](https://meta.discourse.org/t/how-to-add-route-to-root-path/186141/4 "2021-04-08T22:42:58Z")

</div>

另一种做法如下：

> [@pfaffman](#):
>
> ```plaintext
> Discourse::Application.routes.prepend do
> get "/ssh-key/:hostname" => "pfaffmanager/serverkeys#get_pub_key_by_hostname", constraints: { hostname: /[^\/]+/ }
> end
> 
> ```
