【问题标题】:Rails 4 nested route for managing HABTM relationship用于管理 HABTM 关系的 Rails 4 嵌套路由
【发布时间】:2016-12-01 16:33:21
【问题描述】:

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

现在,为了让客户能够为自己启用/禁用给定的 crons 列表,我想让控制器与 app/controllers/cron_jobs_controller.rb 中的 CronJobsController 分开。我希望它整齐地放置在客户端文件夹下的命名空间中,并简单地将其命名为 CronsController (app/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 资源?

【问题讨论】:

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


    【解决方案1】:
    resources :clients do
        scope module: :clients do
          resources :crons, only: ['index'] do
            member do
              post :append
              delete :remove
            end
          end
        end
      end
    

    【讨论】:

    • 谢谢。投票反对的 IDK 但这对我很有用。此外,我将member 块更改为post '/', to: 'crons#append',现在我可以发帖到/clients/:client_id/crons/:id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多