开发者

Override route helper methods

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开发者_StackOverflow中文版 "answer_path(a)" method to get

"questions/123#answer-345"

instead of

"answers/345"

How to do it ?


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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜