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
Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.
rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.
Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With