Handling Nested Resources in CFWheels

Several frameworks these days are including a routing system to make it easy to implement user friendly urls, or as some like to call them, search engine safe urls. These routing systems can also make refactoring much simpler as well if you use them properly.
I have been playing around with CFWheels lately and was wondering how I could take advantage of nested resources in this framework. Nested resources is something I picked up while working on some Rails projects, its a way to automatically handle related objects in your forms. Let me show you a quick example.
Say we are building a bug tracker. We have 2 objects, a Projects object and a Ticket object. Here is how the associations are setup.


and now our Ticket.cfc

Now normally if you were adding a ticket, you could use a URL like this:
And you could pass in the projectID as a hidden field or something like that to handle the association.
But, there is a much easier way to handle this. First lets take advantage of the routing system and create a few routes. I like named routes in my applications much better than the defaults. If I ever refactor a controller and rename an action, etc. I can change the route and every link in my site that points to that route is automatically updated for me. Hows that for a time saver?

These 3 routes handle the nesting for us. Notice how the project part of the url is always first? Then the nested resource since tickets belong to projects. This URL structure will ensure that our projectID is always available in the params scope. Our URl will now look like this if we are adding a ticket to a project.
Heres a typical link that would point to our form to create a new ticket.

#linkTo(text="New Ticket", route="new_project_ticket", projectid=params.projectid)

To setup our form for the new ticket an automatically populate the projectID hidden field, we can write our controller action like this.

That takes advantage of the built-in associations in Wheels and builds the new ticket object through the project object for us. You form would be a standard Wheels form but will automatically have the projectID set in the hidden field for you.

One thought on “Handling Nested Resources in CFWheels”

Leave a Reply

Your email address will not be published. Required fields are marked *