views:

39

answers:

3
+1  Q: 

Rails routing help

I want the url of a user post to be like this:

example.com/users/username/post-name

How should I set this up?

Currently, the post model contains:

def to_param
    name.parameterize
end 

(to hyphenate the post name accordingly)

routes.rb contains:

  map.resources :users
  map.resources :posts

Preferably, I would like to say post_path(post) and this would generate the appropriate path for me by finding the post.user automatically.

What do I need to do to make this happen?

Also added

map.resources :users do |user|
    user.resources :posts
end
A: 

That to_param looks okay, but the builtin helpers don't link to nested resources like you want, you'd have to use user_post_path(user, post). Ofcourse, you could write your own post_path helper method which does work the way you want.

def post_path(post)
  url_for [post.user, post]
end
Marten Veldthuis
This almost works. It gives me a url like /users/username/posts/post-name. I don't want the 'posts' part of the url to exist.
aaronmase
+1  A: 

Hi To make your application recognize routes like

example.com/users/username/post-name

you should add to your routes.rb

 map.connect 'users/:username/:post', :controller => "users", :action => "test"

Then you can access params[:username] and params[:post] inside your controllers test action You should define it after map.resources :users but before map ':controller/:action/:id' but you must write your own helper then

Bohdan Pohorilets
+1  A: 

One way more:

map.resources :users do |user|
  user.connect ':name/:action', :controller => 'posts', :defaults => {:action => 'show'}
end 

Available routes:
example.com/users/username/post-name
example.com/users/username/post-name/edit (any action)

Tumtu
in this case if you acces route like /users/first/second then params[:name] = second and params[:user_id] = first
Bohdan Pohorilets