While building a Rails app, I recently encountered a situation in which I want a resource to be accessible in the context of multiple other resources, and behave slightly differently depending on the context. What is the best way of handling something like this? Currently, I’m handling this by nesting the resource inside of more than one parent resource. This has been getting somewhat cumbersome however, and I want to know if there is a better way of doing this.
Example:
Say I have a UserRights model, and I want users to be able to view, create, and edit these rights in the context of either an individual user, or a whole 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 generates the routes:
users/:user_id/user_rights/:id
groups/:group_id/user_rights/:id
Then, in the controller, I handle things slightly differently based on context.
This allows me to provide a rather nice UI on the client side where the user can view and edit all rights that a group has, or all rights that a user has. Is there a better way of doing this?
No. The more contexts you require, the more complexity it unfortunately, requires. If you add an API to your app, it can get even more complex, because often you want basic, not nested resources. The only solution I have found is to try and strike a balance by not creating the routes that will be used most, and then eliminate the rest by having those requests conform. Confusing, yes!