Locating nested resources - how do you do it?

I struggle with this all the time and I haven’t come up with a solution I’m happy with so I thought I’d ask the group for some opinions.

Let’s assume I have something like this in my routes file:

map.resources :users do |u|
u.resources :projects do |p|
p.resources :tasks
end
end

When you go to /users/1/projects

you might consider looking up the project like this:

@project = Project.find(params[:id])

or like this:

@proejct = current_user.projects.find(params[:id])

because no other user should be able to see this users’ projects…

But what do you do when you start looking at tasks? /users/1/projects/1/tasks

Do you find the project through the user and then show the tasks?

What about a specific task? (/users/1/projects/1/tasks/1)

Do you just look up the task and then figure out if it belongs to a project the user owns? Do you store the user ID an any object the user account “owns” to make the lookups easier?

I’ve tried lots of these methods, but the one I’m happiest with is just leaving the finders alone and using before_filters to figure out if you have access, but that sometimes results in more queries.

Just lookin’ for some of your thoughts. I hope I’m being clear enough on what I’m asking.

Thanks much!

-Brian Hogan

Brian Hogan wrote:

Let's assume I have something like this in my routes file:

map.resources :users do |u|
   u.resources :projects do |p|
      p.resources :tasks
  end
end

...

But what do you do when you start looking at tasks? /users/1/projects/1/tasks

Do you find the project through the user and then show the tasks?

@user = User.find(params[:user_id])
@project = @user.projects.find(params[:project_id])
@tasks = @project.tasks

Pete Yandell
http://notahat.com/