Nesting Rails Resources in Multiple Locations

When creating a Rails application, I recently came across a situation in which I want a resource to be available in the context of several other resources and behave somewhat differently depending on the context. What is the best way to deal with something like this? I am currently processing this by nesting a resource within more than one parent resource. However, this has become somewhat cumbersome, and I want to know if there is a better way to do this.


Example:

Let's say I have a UserRights model, and I want users to be able to view, create and edit these rights in the context of both an individual user and an entire group of users:

resources :users do resources :user_rights, context: :user # params[:context] = :user end resources :groups do resources :user_rights, context: :group end 

This creates routes:

 users/:user_id/user_rights/:id groups/:group_id/user_rights/:id 

Then in the controller, I handle things a little differently based on context.

This allows me to provide a pretty nice client-side user interface where the user can view and edit all the rights that the group has, or all the rights that the user has. Is there a better way to do this?

+4
source share
1 answer

No. The more contexts you require, the more difficult it is, unfortunately, requires. If you add an API to your application, it can become even more complex because you often need basic rather than nested resources. The only solution I found was to try to find a balance without creating the routes that would be used the most, and then eliminate the rest if those requests matched. Embarrassing, yes!

0
source

All Articles