Search code examples
ruby-on-railsroutesnested-resources

Rails nested routing to html id


given a blog style application:

#models
class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

#routes.rb
map.resources :posts do |posts|
  posts.resources :comments
end

how do I generate routes to an id on a page? Examples

/posts/1#comments
/posts/2#comment14

Solution

  • I don't think the routes generate methods for anchors like that, but you can add anchors into the url generators for posts.

     post_path(@post, :anchor => "comments")
     post_path(@post, :anchor => "comment#{@comment_id}")