开发者

Rails 3 routing: add action to all resources in namespace

开发者 https://www.devze.com 2023-03-29 04:09 出处:网络
I\'m designing my admin panel for a cms and I want to have for example Downloads, Images and Articles. Each of these elements can be categorized, so I have an action \"categories\" on each controller(

I'm designing my admin panel for a cms and I want to have for example Downloads, Images and Articles. Each of these elements can be categorized, so I have an action "categories" on each controller(Downloads, Images and Articles).

In my routes file I have the following:

 namespace :admin do    
     resources :downloads
     resources :images
     resources :articles
 end

My problem is that the above code only creates routes for index, show, edit, update and destroy. Is there a method of adding the categories action to all resources once, without declaring it 3 times?开发者_开发百科


namespace :admin do
  [:downloads, :images, :articles].each do |resource|
    resources resource do
      get :categories, :on => :collection
    end
  end
end


If you need more fine-grained control, you can also provide your own custom resources method:

Rails.application.routes.draw do

  def resources_with_count(*params, &block)
    resources *params do
      collection do
        get :count
      end
    end
    resources *params, &block
  end

  # This will now generate regular resources, but also add the /users/count route as well
  resources_with_count :users do
    resources :comments
  end
  resources_with_count :posts
end
0

精彩评论

暂无评论...
验证码 换一张
取 消