Naming params of nested routes

后端 未结 3 709
深忆病人
深忆病人 2021-01-14 06:54
resources :leagues do
  resources :schedule
end

This generates:

leagues/:id
leagues/:league_id/schedule/:id

How c

相关标签:
3条回答
  • 2021-01-14 07:05

    No, please do not do this.

    The reason for it being this way is that it provides a common interface for nested resources across every single application. By making it different in your application, you're effectively going "against the grain" of Rails. Rails has a strict set of conventions that you should stick to. When you stray from this path, things get messy.


    However, if you do want to shoot yourself in the foot, metaphorically speaking, you will need to define the routes manually. Here's the routes for the seven standard actions in a controller:

    get 'leagues/:id/schedules', :to => "schedules#index", :as => "league_schedules"
    get 'leagues/:id/schedule/:schedule_id', :to => "schedules#show", :as => "league_schedule"
    get 'leagues/:id/schedules/new', :to => "schedules#new", :as => "new_league_schedule"
    post 'leagues/:id/schedules', :to => "schedules#create"
    get 'leagues/:id/schedule/:schedule_id/edit', :to => "schedules#edit", :as => "ed it_league_schedule"
    put 'leagues/:id/schedule/:schedule_id', :to => "schedules#update"
    delete 'leagues/:id/schedule/:schedule_id', :to => "schedules#destroy"
    

    As you can see, it's quite ugly. But, if you really really really want to do it this way, that's how you'd do it.

    0 讨论(0)
  • 2021-01-14 07:09

    It appends the ID to the nested_param which is a bummer because I would like mine to be without the singular name. It looks like they really don't want you to make it only like :id as it could have conflicts. Plus it would be a bit of a diff from the normal restful routing that rails likes to use.

    https://github.com/rails/rails/blob/5368f2508651c92fbae40cd679afbafdd7e98e77/actionpack/lib/action_dispatch/routing/mapper.rb#L1207

    namespace :account, defaults: { type: 'account' }do
      resources :auth, param: :lies_id, only: [] do
        get :google
      end
    end
    

    Rake routes returns the following

    $ rake routes | grep /account/auth
    account_auth_google GET  /account/auth/:auth_lies_id/google(.:format)
    

    So the solution which seams simpler is to just change the controller to use the nested param name it creates.

    0 讨论(0)
  • 2021-01-14 07:25

    You can set "param" option on resource route to override the default "id" param:

    resources :leagues do
      resources :schedule, param: schedule_id
    end
    

    refs to the Rails Routing Doc: http://guides.rubyonrails.org/routing.html#overriding-named-route-parameters

    0 讨论(0)
提交回复
热议问题