If I have a nested resource like so:
resources :users
resources :posts
end
and a user has_many posts, it is possible to have Rails start numbering based on the parent association in the URL? For example, currently, nesting resources just grabs the ID:
@user.posts.find(params[:id])
This correctly namespaces the posts, only allowing posts from @user… however, is there a way such that the post_id is independent? I.E. I want each user’s posts to start at 1, where:
/users/1/posts/1
/users/2/posts/1
Actually refer to two different posts?
It can be quite a bit of work, but basically you can do it with these steps:
user_post_id)Post‘sto_parammethod to use the new value you just created. (It has to be a string.)to_paramis the method that theurlandpathhelpers use.before_savefilter that will actually increment theuser_post_idvalue for each new post.Change all your controller methods to find on
user_post_idYou can see the source here: Custom Nested Resource URL example
Code
migration:
post.rb:
A couple controller methods
posts_controller.rb: