重写路由助手方法

发布于 2024-10-20 04:43:47 字数 358 浏览 2 评论 0原文

问题有很多评论。

URL“questions/123”显示一个问题。

一个网址:

“问题/123#answer-345”

显示问题并突出显示答案。 345 - 是 Answer 模型的 id,“answer-345”是 HTML 元素的 id 属性。

我需要重写“answer_path(a)”方法才能获得

“问题/123#answer-345”

而不是

“答案/345”

怎么办?

Question has many Comments.

A URL "questions/123" shows a question.

A URL:

"questions/123#answer-345"

shows a question and highlights an answer. 345 - is id of Answer model, "answer-345" is id attribute of HTML element.

I need to override "answer_path(a)" method to get

"questions/123#answer-345"

instead of

"answers/345"

How to do it ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

久而酒知 2024-10-27 04:43:47

所有 url 和路径帮助器方法都接受可选参数。
您正在寻找的是 anchor 参数:

question_path(123, :anchor => "answer-345")

它记录在 URLHelper#link_to 示例

使用此参数,您应该能够通过以下方式创建 answer_path 帮助器:

module ApplicationHelper

  def answer_path(answer)
    question_path(answer.question, :anchor => "answer-#{answer.id}")
  end

end

All url and path helper methods accept optional arguments.
What you're looking for is the anchor argument:

question_path(123, :anchor => "answer-345")

It's documented in the URLHelper#link_to examples.

Using this argument, you should be able to create an answer_path helper via:

module ApplicationHelper

  def answer_path(answer)
    question_path(answer.question, :anchor => "answer-#{answer.id}")
  end

end
初熏 2024-10-27 04:43:47

提供涵盖更多领域的解决方案(不仅适用于视图,还适用于控制器/控制台)

module CustomUrlHelper
  def answer_path(answer, options = {})
    options.merge!(anchor: "answer-#{answer.id}")
    question_path(answer.question, options)
  end
end

# Works at Rails 4.2.6, for earliers versions see http://stackoverflow.com/a/31957323/474597
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)

Offering a solution which covers more areas (works not only in views but also in controller/console)

module CustomUrlHelper
  def answer_path(answer, options = {})
    options.merge!(anchor: "answer-#{answer.id}")
    question_path(answer.question, options)
  end
end

# Works at Rails 4.2.6, for earliers versions see http://stackoverflow.com/a/31957323/474597
Rails.application.routes.named_routes.url_helpers_module.send(:include, CustomUrlHelper)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文