Override route helper methods

落花浮王杯 提交于 2019-11-29 17:10:49

问题


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 ?


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/5203819/override-route-helper-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!