7

I need to add the following member methods to a number of resources, is there a way to DRY this up?

 member do
    get   :votes
    post  :up_vote
    post  :down_vote
  end

In my routes.rb

resources :news do
  resources :comments do
     member do
        get   :votes
        post  :up_vote
        post  :down_vote
      end
  end
end

resources :downloads do
  resources :whatever do
     member do
        get   :votes
        post  :up_vote
        post  :down_vote
      end
  end
end

EDIT

I've actually moved it out into a module like so:

module Votable
  module RoutingMethods
    def votable_resources
      member do
        get   "up_votes"
        get   "down_votes"
        post  "up_vote"
        post  "down_vote"
      end
    end
  end # RoutingMethods
end

Now, my routes.rb looks like this:

require 'votable'

include Votable::RoutingMethods

MyApp::Application.routes.draw do

  namespace :main, :path => "/" do
    resources :users do 
      resources :comments do
        votable_resources
      end
    end
  end

end

See my inline comments, but I want the named route to look like: main_users_comments_up_votes

Dex
  • 11,863
  • 15
  • 65
  • 88
  • Please see my edit. Could you edit your question with how you're doing the named routes? – monocle Nov 24 '10 at 04:03
  • Does nesting 'votable_resources :comments' within 'resources :comments' get you any closer? – monocle Nov 24 '10 at 04:28
  • Just made another edit. The problem with nesting it inside `resources :comments` is that the RESTful actions were breaking on me. – Dex Nov 24 '10 at 04:30
  • I went back and simplified it, got too complicated. Not sure what is up with the named_routes, but I don't think it pertains to the original question. – Dex Nov 24 '10 at 04:46
  • What's the controller and action for 'main_users_comments_up_votes'? – monocle Nov 24 '10 at 04:50

1 Answers1

7

Can't you just define a method in your routes files?

def foo
  member do
   get   :votes
   post  :up_vote
   post  :down_vote
  end
end


resources :news do
 resources :comments do
   foo
 end
end

Edit

I haven't used this technique before. It just seemed to work when I did 'rake routes'. Anyways, the routes file is just Ruby code. Just be careful about the name of the method you define because it's defined in the instance of ActionDispatch::Routing::Mapper.

# routes.rb

MyApp::Application.routes.draw do
  puts self
  puts y self.methods.sort
end

# Terminal
> rake routes
monocle
  • 5,826
  • 2
  • 23
  • 21
  • One problem I'm having is keeping it in scope for named routes. Looking at using Procs instead. – Dex Nov 24 '10 at 03:47