3

In routes.rb,

resources :projects

gives the following routes

/projects/
/projects/:id

While using nested resources like

resources :projects do
  resources :photos
end

it gives the following routes

/projects/
/projects/:id
/projects/:project_id/photos
/projects/:project_id/photos/:id

This gives me the problem because I have to write controller specific before_filter choosing between params[:id] and params[:project_id] for doing Project.find(params[:project_id] || param[:id])

Is there any way to change the routes to have :project_id itself for all routes?

/projects/
**/projects/:project_id**
/projects/:project_id/photos
/projects/:project_id/photos/:id
Jey Geethan
  • 2,235
  • 5
  • 33
  • 60
  • 1
    This shouldn't be a problem because your `Project.find params[:id]` will be in your `ProjectsController` and your `Project.find params[:project_id]` will be in your `PhotosController`. If you have something truly unique, you can use http://guides.rubyonrails.org/routing.html#adding-more-restful-actions and `get :photos, on: :member` which will make `/projects/:id/photos` and use `:id` on all `/projects/` path instead of `:project_id`. – Chloe Jun 28 '17 at 04:09
  • You could try this trick: https://stackoverflow.com/a/32664225/2131983 – khiav reoy Feb 12 '18 at 03:05

3 Answers3

2

Another way is define method, that find current project by :project_id, in ApplicationController

def current_project
  @current_project ||= Project.find params[:project_id]
end

And redefine this method in ProjectController

def current_project
  @current_project ||= Project.find params[:id]
end

Then, you can use current_project in filters for all your controllers

mikdiet
  • 9,859
  • 8
  • 59
  • 68
1

Name of resource's id param can't be changed

But you can redefine it as non-restful path before resourses

get "projects/:project_id" => "projects#show"
# etc. for all other 3 methods
mikdiet
  • 9,859
  • 8
  • 59
  • 68
  • So I have to manually rewrite all the routes eh? If thats the only solution, I am worried this will not be DRY. – Jey Geethan Mar 23 '12 at 05:18
0

I think what you're looking for is Shallow Nesting: http://edgeguides.rubyonrails.org/routing.html#nested-resources

Look down to 2.7.2 Shallow Nesting

mathieugagne
  • 2,465
  • 1
  • 17
  • 18