Rails 3.1 - How to organize multiple index actions for the same model?

I have a User model that has multiple projects. The project model belongs to the user model. I am currently using the index_controller.rb action to display all projects that have been created for all users (Project.all).

On a separate page, I would also like to show all projects owned by a specific user (for example, go to the page and view all projects owned by a given user).

I am having a hard time figuring out which controller / action / view to use and how to set up the routes because I already used the index action for project_controller to show all projects. Does anyone have any suggestions?


source to share

4 answers

You can make / users / {: id} / projects, which will appear in the actions of users' projects. The route must be a configurable member action

resources :users do
  member do
    get 'projects'




instead of having different listing pages. use the same index page based on different criteria, i.e. filters.


match ":filter/projects", :to => "projects#index"


inside the controller something like

case params[:filter]
when "all"
  @projects = Project.all
when "user" 
  @projects = current_user.projects
when "batch"
  # ..
  # ..




How do you show projects owned by a specific user on a page User#show


Something like this is possible:

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])

  # rest of class omitted...


You can then access the user-owned projects in the view for the show page by calling @user.projects




In users

you have to nest projects

to get working code / paths like: /users/1/projects

without any additional coding, so you need to change your resource strings in routes.rb


resources :users, :shallow => true do 
  resources :projects


and then in the project # show action instead Project.find(params[:id])

you need to getProject.find(params[:user_id])

It seems right



All Articles