避免在rails 3中使用复杂的嵌套路由/资源重复

时间:2011-07-15 10:21:08

标签: ruby-on-rails-3 resources routes nested

我目前有这些路线(简化版)

  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

许可证控制器可以处理嵌套在客户端中的情况,如果是,那么只有那些客户端的许可证可以访问。

这似乎不是很干,有没有更好的方法来表示这些路线,这样如果我更改许可证的路由签名,我也不必在客户端更改它?

1 个答案:

答案 0 :(得分:1)

好吧,我终于花了一些时间来看这个,并记得Devise gem(和其他人)有自定义'路线助手'(比如devise_for)所以我借用他们的方法并发现它非常实用:

对于我的项目,这都在routes.rb中,但如果需要,'helper'方法可能会转到其他地方。

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