Killerpixler Killerpixler - 8 days ago 6
Ruby Question

Rails 4 nested route for managing HABTM relationship

I have a

Client
model which has a
has_and_belongs_to_many
relationship with the
CronJob
model.

Now to give a client the ability to enable/disbale a given list of crons for themselves I want to make a controler separate from the
CronJobsController
in
app/controllers/cron_jobs_controller.rb
. I want it to sit neatly namespaced under the clients folder and simply call it
CronsController
(
app/controllers/clients/crons_controller.rb
). The question is how to set up the routes file so I get these routes available to me:


  • 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



Right now my
routes.rb
has this, which is close but not quite

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


which results in:

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


The problem here is
/clients/:client_id/clients/crons/
with this extra
clients
in the middle.

I know I could just leave the namespace out of it and would get the desired route but that would make the folder architecture quite unwieldy since there will be a number of these HABTM relationships on various models.

Alternatively is there a way I can tell the routes file to look in the clients subfolder for the crons resources?

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