I have some models like News and Downloads which have_many comments :as => :commentable. Comment belongs_to :commentable and is :polymorphic. Like the comments, there are subscriptions. So my routes look like this:
resources :news do
resources :comments do
post :like, :on => :member
delete :like, :on => :member
end
resources :subscriptions
...
end
resources :downloads do
resources :comments do
post :like, :on => :member
delete :like, :on => :member
end
resources :subscriptions开发者_如何学JAVA
...
end
...
Is there a way to DRY this up? I tried defining
def comment_resources
resources :comments do
# ...
end
resources :subscriptions
end
at then top of routes.rb and then calling comment_resources but it seems dirty to me because it isn't namespaced / in a class correctly.
1) If you have exactly the same inner routes in both news and downloads, you can make
%w(news downloads).each do |res|
resources res do
resources :comments do
post :like, :on => :member
delete :like, :on => :member
end
resources :subscriptions
...
end
end
2) Otherwise you can look at https://github.com/rails/routing_concerns (will be included as part of rails-4):
concern :commentable do
resources :comments do
post :like, :on => :member
delete :like, :on => :member
end
resources :subscriptions
end
resources :news, concerns: :commentable do
...
end
resources :downloads, concerns: :commentable do
...
end
You were on the right track. You can define the method within the routes.draw do/end block so that it isn't tangling in the global namespace.
Application.routes.draw do
def comment_resources
resources :comments do
post :like, :on => :member
delete :like, :on => :member
end
resources :subscriptions
...
end
resources :downloads do
comment_resources
end
resources :news do
comment_resources
end
end
taken from: http://symmetricinfinity.com/2013/04/16/drying-up-your-api-routes-in-rails.html
精彩评论