Question

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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top