Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Restful Routes with variable name
3 Posts
Restful Routes with variable name

I'm trying to make a gaming-news/reviews website. There's one model for articles, called Post. A Post has comments and belongs to a category.

With nested routes I created the following route, which works perfectly well. map.resources :posts, :has_many => :comments

Besides that I'm using the following 2 routes to get /news/:id and /reviews/:id map.resources :news, :controller => :posts, :category_id => 1 map.resources :reviews, :controller => :posts, :category_id => 2

These are doing their job just as good as the nested route for comments.

What I'm coping with now however is the following. I'd like to get URLs like /news/2/comments. I don't see how I can ever do something like this now. I can't put an array in the name of the resource-route; like:

map.resources [:news, :reviews], :controller => :posts, :category_id => [1,2] do |post| map.resources :comments end

Is there anyone here that can help me?

ps. This is my first topic, I hope I'm doing good.

If I understand correctly, you would like to have three separate routes that all point at the Posts controller, with nested routes under each which all point at the Comments controller. I can think of two possible ways to do this.

You can collect the common options for each route and use #with_options to share them with each definition (I believe this will work, but I don't generally use the :has_many option in routing, so your mileage may vary). For example:

map.with_options(:controller => :posts, :has_many => :comments) do |post_options|
  post_options.resources :posts
  post_options.resources :news, :category => 1
  post_options.resources :reviews, :category => 2
end

Alternately, you could use the block syntax for declaring nested routes and pass a common block to each top-level posts resource. For example:

comments_nesting = Proc.new { |post| post.resources :comments }
map.resources :posts, &comments_nesting
map.resources :news, :controller => :posts, :category_id => 1, &comments_nesting
map.resources :reviews, :controller => :posts, :category_id => 2, &comments_nesting

Does that help at all?

Ah, awesome, thanks a lot for you reply. I tried the first option and it seems to be doing the trick.

Turns out I got pretty close to that option before, what seems to be a problem still is the :category => 1 option. When I do a rake routes I get the following options (among others);

news GET /news/:id(.:format) {:controller=>"posts", :action=>"show"}

   PUT    /news/:id(.:format)                             {:controller=>"posts", :action=>"update"}
   DELETE /news/:id(.:format)                             {:controller=>"posts", :action=>"destroy"}

Any clue on that?

3 Posts
Login to add your message