Ask A Question

Notifications

You’re not receiving notifications from this thread.

Nesting resources & controllers best practice

Tom Goddard asked in General

Hi all,

I'm relatively new to rails so apologies if this is a very basic concept / been asked before, I've had a look around and can't really find any best practices for when to use nested controllers.

For example, If you had a "Websites" controller and a "Pages" controller, the pages wouldn't exist without the Website, so would these be nested together?

This would match the routes and seems to make sense from a logic standpoint.

Thanks!

Reply

Hey Tom,

You're on the right path. The controller would be "nested" or similar. Basically, you'd lookup the Website before you lookup the Page (so you can make sure you only display the website's pages and no others).

You can do that with nested routes like /websites/1/pages/2. Here, your controller would look up the website with Website.find(params[:website_id]) from the URL.

Also, you could use domains / subdomains to lookup the website. Then you wouldn't need nested routes and you could have subdomain.example.com/pages/2. In this case, your controller would do Website.find_by(subdomain: request.subdomain)

Reply

Hey Chris,

Thanks for your reply! makes a lot of sense.

In terms of folder structure, are there any pros / cons of putting nested resources controllers in their respective nested folders?

For example having your websites_controller in the controllers folder (controllers/websites_controller), then putting the pages_controller inside a folder such as controllers/websites/pages_controller.

Apologies for the long winded question, hope this makes sense.

Reply

I almost always nest them in folders. It's very helpful when your app grows. Often times you might have 2 or 3 controllers with the same name that do different things and the nesting in folders helps separate them out.

For example,

websites/pages_controller might be for website editor
subdomains/pages_controller might be for people viewing the website
admin/pages_controller might be for the business owner (you) to do customer support

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.