How do I make these routes + helpers with resourceful semantics/syntax?

78 Views Asked by At

I want a routes like:

get '/posts/new'           => 'posts#new'
get '/:username/posts/:id' => 'posts#show'
get '/:username/posts'     => 'posts#index'

Accessible via helpers like:

new_post_path    #=> new   -
post_path(post)  #=> show  - :username implied from post
posts_path       #=> index - :username implied from session
posts_path(user) #=> index - :username explicit

I'd like to do this with resourceful semantics, instead of specifying each route by hand. Also I'm not sure how to make the url helpers smart.

Thoughs?

1

There are 1 best solutions below

2
On

I'm assuming what you want is to have nested routes. This should get you closer to what you're looking for.

in your routes.rb file:

resources :users do
  resoures :posts
end

This will make paths like this:

/users
/users/:user_id
/users/:user_id/posts
/users/:user_id/posts/:id

Then you can tweak your routes from there so that /posts/new points to your posts controller with something like this:

(untested and not sure this is 100% correct so someone please chime in)

resources :users do
  resoures :posts do
    match "/posts/new", :to => "posts#new"
  end
end