Okay, so I am new to Rails and am creating a project management system with the framework. For a couple of my models, views, and controllers I used scaffolding and had no problems. For other parts, I coded all of the parts myself.
So as an overview of my project, at the root of it all you can have many projects. Within all of these projects you can create multiple to-do lists. Within each to-do list, you can have multiple tasks. This is what I meant by "hierarchical" in the title.
I just created my lists page, and when I go to the URL directly in my browser (ex: http://localhost:3000/projects/3/lists/20/tasks/1
) the task is displayed correctly. However, I do not know how to format my link that is in one of my to-do list views (the tasks are usually shown below the to-do list but now I want them to show on their own view).
Here is the code I currently have:
<%= link_to "#{task.description}", project_list_tasks_url(@list.id,task.id) %>
I know that the link_to "#{task.description}"
is correct because I tried using it with a static URL (Google or something), but project_list_tasks_url(@list.id,task.id)
is where I'm having trouble.
Can anybody help me out? I can provide as much code as you'd like from my to-do list or task controllers and views.
A couple of tips to help make routing less confusing. It can be a bit unnerving to get used to.
Routing Rule #1
Always check the output of rake routes
to be sure how to call your various routing methods. You might think you know how your routes will play out by looking at routes.rb
but you won't know until you look at the compiled routes table.
In your case you're expecting a route with the format:
/projects/:project_id/lists/:list_id/tasks/:id
Be sure that's the case. If it is, your call should look like:
project_list_task_path(@project, @list, task)
Note that the arguments here are :project_id
, :list_id
and :id
, so all three are required in this case. Any in brackets in the path specification can be ignored, like :format
usually is.
Routing Rule #2
Use the _path
methods unless you strictly require the full URL. They're shorter and the output is easier to read and debug. They also don't inadvertently flip the URL in the browser and cause session problems if you don't properly differentiate between www.mysite.com
and site.com
.
Routing Rule #3
Don't forget there's a huge difference between @project
and @project.id
when it's supplied to a routing path method.
The router will always call the to_param
method if it's available and this can be over-ridden in your model to produce pretty or friendly URLs. id
is for your database and your database alone. to_param
is for routing but you shouldn't be calling it manually unless you're doing something exceptionally irregular.