Rails 4用于管理HABTM关系的嵌套路由

时间:2016-12-01 16:33:22

标签: ruby-on-rails ruby ruby-on-rails-4 routing

我有一个与Client模型有has_and_belongs_to_many关系的CronJob模型。

现在,为了让客户能够为自己启用/取消给定的cron列表,我想让控制器与CronJobsController中的app/controllers/cron_jobs_controller.rb分开。我希望它在客户端文件夹下整齐地命名,并简单地称之为CronsControllerapp/controllers/clients/crons_controller.rb)。问题是如何设置路线文件,以便我可以使用这些路线:

  • clients - > /clients
  • client_crons - > /clients/:client_id/crons
  • append_client_cron - > post - > /clients/:client_id/crons/:id
  • remove_client_cron - > delete - > /clients/:client_id/crons/:id

现在我的routes.rb有这个,这很接近但不完全

resources :clients do
    namespace :clients do
        resources :crons, only: ['index'] do
          member do
            post :append
            delete :remove
          end
        end
    end
  end

导致:

    append_client_clients_cron POST   /clients/:client_id/clients/crons/:id/append(.:format)     clients/crons#append
    remove_client_clients_cron DELETE /clients/:client_id/clients/crons/:id/remove(.:format)     clients/crons#remove
          client_clients_crons GET    /clients/:client_id/clients/crons(.:format)                clients/crons#index

这里的问题是/clients/:client_id/clients/crons/,中间有这个额外的clients

我知道我可以将名称空间从它中删除并获得所需的路线,但这会使文件夹架构变得非常笨拙,因为在各种模型上会有很多这些HABTM关系。

或者有一种方法可以告诉路由文件在客户端子文件夹中查找crons资源吗?

1 个答案:

答案 0 :(得分:1)

resources :clients do
    scope module: :clients do
      resources :crons, only: ['index'] do
        member do
          post :append
          delete :remove
        end
      end
    end
  end