开发者

Avoiding repetition with complex nested routes/resources in rails 3

开发者 https://www.devze.com 2023-03-20 07:40 出处:网络
I currently have these routes (a simplified version) resources :licenses, :except => [:show] do collection do

I currently have these routes (a simplified version)

  resources :licenses, :except => [:show] do
    collection do
      post :search
      get :search
    end
    member do
      post :activate
      post :revoke
      post :suspend
    end
  end

  resources :clients, :except => [:show] do
    resources :licenses, :except => [:show] do
      collection do
        post :search
        get  :search
      end
      member do
        post :activate
        post :revoke
        post :suspend
      end
    end
  end

Where the licenses controller can deal with being nested in a client or not, and if it is then only those client's licenses are accessible.

This doesn't seem very DRY though, is there a better way to represent these routes so that if I change the routing sig开发者_JAVA百科nature of Licenses I don't have to change it in clients too?


Ok, I finally spent some more time looking in to this and remembered that the Devise gem (and others) have custom 'route helpers' (like devise_for) so I borrowed their method and found it to be quite practical:

For my project this is all in routes.rb, but the 'helper' methods could probably go elsewhere if required.

module ActionDispatch::Routing

  class Mapper

    def report_routes
      resources :reports, :except => [:create] do
        member do
          get :download
        end
      end
    end

    def website_routes
      resources :websites do
        member do
          post :enable
          post :disable
        end
      end

    end

  end

end

MyApp::Application.routes.draw do

  website_routes

  report_routes

  resources :clients do
    website_routes
    report_routes
  end

end
0

精彩评论

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