Rails 3 - How to change the: id parameter in resources

In routes.rb

,

resources :projects

gives the following routes

/projects/
/projects/:id

      

When using nested resources such as

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 a problem because I have to write a specific controller before_filter choosing between params[:id]

and params[:project_id]

to executeProject.find(params[:project_id] || param[:id])

Is there a way to change the routes to have :project_id

for all routes?

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

      

+3


source to share


3 answers


Another way is the definition method, which finds the current project: project_id, in ApplicationController

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

      

And override 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

+2


source


Can't change the name of the id resource parameter

But you can override it as an unoccupied path before resources



get "projects/:project_id" => "projects#show"
# etc. for all other 3 methods

      

+1


source


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

Look down at 2.7.2 Invalid attachment

0


source







All Articles