Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use anchors for IDs in routes in Rails 3?

Imagine a blog with posts and comments. An individual comment's URL might be posts/741/comments/1220.

However, I'd like to make the URL posts/741#1220, or even posts/741#comment-1230.

What's the least intrusive way of doing this, so that redirect_to comment_path(my_comment) points to the correct URL?

like image 303
ClosureCowboy Avatar asked Feb 12 '11 22:02

ClosureCowboy


People also ask

How do routes work in Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

How many types of routes are there in Rails?

Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.


1 Answers

You could simply use

redirect_to post_path(comment.post, :anchor => "comment-#{comment.id}") 

to manually build the URL with the anchor. That way, you can still have the absolute URL to your comments as posts/:post_id/comments/:comment_id in your routes. You can also create a helper method in e.g. application_controller.rb

class ApplicationController   helper :comment_link    def comment_link(comment)     post_path(comment.post, :anchor => "comment-#{comment.id}")   end end 
like image 200
Holger Just Avatar answered Sep 18 '22 20:09

Holger Just