15

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 ?

AntonAL
  • 16,692
  • 21
  • 80
  • 114

2 Answers2

16

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
rubiii
  • 6,903
  • 2
  • 38
  • 51
  • No, i do need it. answer_path should actually point to it's Question's path, and also append hash-part. – AntonAL Mar 05 '11 at 12:37
  • Updated the answer with a helper method. Hope that works for you. – rubiii Mar 05 '11 at 12:46
  • 1
    Thanks. Where should this method be located, to have precedence over default answer_path ? – AntonAL Mar 05 '11 at 12:55
  • 1
    You should be able to put it inside the `ApplicationHelper` module or any more specific helper module if the method is not needed on every page. – rubiii Mar 05 '11 at 13:08
  • Here's an [updated link](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) for the API documentation – Matt Dec 14 '12 at 17:44
0

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)
lulalala
  • 17,572
  • 15
  • 110
  • 169