max
max

Reputation: 102443

Overriding Rails route helpers for nested resource

Let's say I have a classic blog application with comments and posts. In this application comments are always nested under a post.

GET /posts/:posts_id/comments/:id ...

I want to in some way override the URL helpers so that I could them as if comments was not a nested resource.

Requirements:

The comments should ONLY use nested urls:

/posts/:posts_id/comments/:id

I should be able to do:

comments_path @comment

And

redirect_to @comment

I have tried:

I can get Rails to generate the route helpers without the prefix with:

resources :posts
scope '/posts/:post_id' do
  resources :comments
end

But comments_path(@comment) would still give me ActionController::UrlGenerationError as post_id is not set.

I could of course manually create my own helper methods but I would like rails to generate the helpers if possible.

From my understanding the routes helpers are a veneer around ActionDispatch::Routing::UrlFor. I have been looking into ActionDispatch::RoutingPolymorphicRoutes but I can't find how the generated helpers "serialize" an model instance into params.

Is it possible to create a model method which is used when the routes helper turns the comment resource into params?

I'm thinking of something along the lines of to_param.

Upvotes: 2

Views: 1203

Answers (1)

sevenseacat
sevenseacat

Reputation: 25049

I've had similar requirements to this before, and what I've done is simply create a custom helper method in my ApplicationController like so:

class ApplicationController < ActionController::Base
  ...

  def comment_path(comment)
    post_comment_path(comment.post, comment)
  end

  helper_method :comment_path
end

That way, you can still use comment_path in your views, helpers, controllers, etc. but it uses the full nested route instead.

I don't know if it can be done with Rails internals, but quite simply I don't think it's worth the hassle.

Upvotes: 2

Related Questions