I have a User model that has_many projects. The Project model belongs_to the User model. I am currently using the projects_controller.rb index action to display all of the projects that have been created across all users (Project.all).
On a separate page, I would also like a way to display all of the projects that belong to a specific user (i.e. go to page and be able to see all of the projects that belong to a given user).
I am having difficulty figuring out which controller/action/view to use and how to set up the routes because I am already used the index action for the projects_controller for the purpose of displaying all of the projects. Does anybody have any suggestions?
You could do /users/{:id}/projects, which would map to the users controller projects action. The route would have to be custom member action
resources :users do
member do
get 'projects'
end
end
rather than having different pages of listing. use same index page based on different criterias i.e. filters.
URL
match ":filter/projects", :to => "projects#index"
inside controller something like
case params[:filter]
when "all"
@projects = Project.all
when "user"
@projects = current_user.projects
when "batch"
# ..
else
# ..
end
How about you display the projects that belong to a particular user on the User#show
page?
Something like this perhaps:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
# rest of class omitted...
Then you can access the projects that belong to the user in the view for the show page by calling @user.projects
.
You should nest projects
under users
to get working code/paths like: /users/1/projects
without any additional coding, so you need to change your resource lines in routes.rb
to:
resources :users, :shallow => true do
resources :projects
end
and then under Projects#show action instead of Project.find(params[:id])
you need to get Project.find(params[:user_id])
That's seems to be correct