'Rails Optional Nested Resources

I'd like to implement optional nested resourcing in my rails app. I have an existing resource, Projects. I would like them to remain standalone but also have the option to nest or 'group' them under a Project Group. I've done nested resources before, but I'm not sure how I would approach nesting them after they've been created. Is this possible or would I need to take a different approach?

EDIT:

For clarity to anyone else who might stumble upon this, I've decided to go for an optional, many_to_many approach. This way, Projects can be created standalone, but can also be added to a Project_Group. I'm planning on doing this through a connection model. So it will be set up like this:

Project has_many_project_groups, through: :groups
Project_Group has_many_projects, through: :groups

and

Group belongs_to :project, optional: true
Group belongs_to :project_group, optional: true

Will keep updated as I go along



Solution 1:[1]

Are you talking about nesting your routes or nesting your folder structure or both? You could achieve this through routes with a product route and a group route with a product route nested inside the group route

resources :products
resources :groups do
  resources :products
end

You can set paths to the various controllers within the resources declarations if you wish to use different product controllers (one nested and one not) and then if you attach a product to a group with a belongs_to group in your product model it would then be accessible to the group assuming you have a corresponding has_many products you would have to set the relationships as optional so do not enforce referential integrity in your database. Can't really offer any further advice as you have not shown what you have actually tried to do and what has failed so that's it really.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jamesc