views:

355

answers:

1

When I was developing my RoR skills with some basic tutorials I encountered a problem. What I am trying to achieve is having comments belonging to posts, with no separate index or individual view. This part was easy.

Here comes tough one. I want post_comment_url to return address with fragment identifier: http://example.com/posts/2#comment-4. It would allow me to use redirect_to in it's simplest form, without :anchor parameter (which would be against ruby way of keeping things simple).

How to do that?

+2  A: 

Instead of altering Rails' default behavior, it'd probably be better to wrap up your needs in a helper method:

# in app/controllers/application_controller.rb
class ApplicationController
  helper :comment_link

  def comment_link(comment)
    post_comment_url(comment.post, comment, :anchor => "comment-#{comment.id}")
  end
end

The call to helper will allow you to access that method in your views as well as your controllers.

nakajima
Probably this is good solution, but I don't like idea of this wrapper because it will break convention of using native post_comment_url method. I also noted, that I would need another helper for post_comment_path. As it is working solution, I don't think it's DRY enough.
samuil
Defying the Rails convention for post_comment_url by returning a post url with a comment anchor tends to lead to bigger headaches than needing to pass the :anchor option everytime (which I'd actually say is the better way anyway, since it describes intent more clearly.)I'd also warn against using DRY as a reason to do almost anything. The term DRY is sort of like the word Agile: it describes a collection of principles and practices, it means almost nothing on its own.
nakajima
DRY is not enigmatic collection of principles. It just means: every information should appear only once in code, and design should make it clear where. If there is no better solution than helper (I'm still quite new to Rails, so can't tell at all if it is easy to implement solution by altering some default methods and consider it clever) I believe it will be contained in some future Rails version.
samuil