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
source to share
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
source to share
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
source to share