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

。_饼干妹妹 提交于 2019-12-05 02:40:58

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/9641018/rails-3-1-how-do-i-organize-multiple-index-actions-for-the-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!