覆盖路由助手方法

问题有很多评论。

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

一个url:

“问题/ 123#答案-345”

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

我需要覆盖“answer_path(a)”方法来获取

“问题/ 123#答案-345”

代替

“答案/ 345”

怎么做 ?

所有url和path helper方法都接受可选参数。
您正在寻找的是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 

提供涵盖更多区域的解决方案(不仅可以在视图中工作,还可以在控制器/控制台中工作)

 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)