如何在 Rails 3.1 中创建无限层次 html 树?
我有一个名为 Metrics
的表,它是一个自引用表。这意味着它与无限子级具有父/子关系。
我有这样的路线:
match "/metrics/:id/children" => "metricchildren#index", :as => "metric_children"
metricchildren
控制器加载指标的子级并呈现索引页面。
该页面看起来像这样(根父级名为 Totals
):
Metric Children?
----------------------------
Total Expense YES
Total Labor NO
现在,我想要做的是让用户单击 Total Expense
,然后 URL 将类似于:
http://example.com/metrics/42-totals/children/78-total-expense
42
是Totals
指标的 ID,78 是Total Expense
指标的 ID。因此,当您深入查看 Total Expense
时,它会创建一个如上所示的表格,当您单击指标时,网址会增长:
http://example.com/metrics/42-totals/children/78-total-expense/98-total-direct
http://example.com/metrics/42-totals/children/78-total-expense/98-total-direct/102-blah
等等...
与 Github 的工作方式非常相似。更好的是不必在 URL 中指定 ID。
关于如何做到这一点有什么宝石或想法吗?我想我有一个关于如何做到这一点的想法,但我不想重新发明那个轮子。
谢谢
I have a table called Metrics
that is a self-referencing table. Meaning it has a parent/child relationship with infinite children.
I have a route like:
match "/metrics/:id/children" => "metricchildren#index", :as => "metric_children"
The metricchildren
contoller loads a metric's children and renders an index page.
That page looks something like (root parent called Totals
):
Metric Children?
----------------------------
Total Expense YES
Total Labor NO
Now, what I want to do is have the user click the Total Expense
and then the URL would look something like:
http://example.com/metrics/42-totals/children/78-total-expense
42
is the ID of the Totals
metric, 78 is the ID of the Total Expense
metric. So when you drill down to Total Expense
it would create a table as above and as you click the metrics, the urls grow like:
http://example.com/metrics/42-totals/children/78-total-expense/98-total-direct
http://example.com/metrics/42-totals/children/78-total-expense/98-total-direct/102-blah
etc...
Very similar to how Github works. Even better would be the ability to not have to specify the ID's in the URL.
Any gems or ideas on how to do this? I think I have an idea on how to do it but I don't want to reinvent that wheel.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至于“递归路由”,请参阅另一篇SO帖子。简短的回答是,使用路由通配实际上非常容易。
现在,我使用 slug 而不是数据库 ID 滚动自己的漂亮永久链接,但我听说过有关 的精彩内容友好_id。
As for the "recursive routes", see this other SO post. Short answer is, it's actually pretty easy with route globbing.
Now, I roll my own pretty permalinks, using a slug instead of the database ID, but I've heard great things about friendly_id.