ruby-on-railsnested-resources

Generating the URL of a nested resource without its parent (without using shallow)


In our application, many resources are nested under a common resource representing an organization. Most URLs include an organization ID the following pattern: /:organization_id/notifications/:id.

My problem is that I always have to give the current organization to generate the URL to any model. For example, the link to an existing notification would be link_to [@organization, @notification].

Since a notification already belongs to an organization, I was wondering if it was possible to generate my URL using link_to @notification and it would actually generate a URL including the organization ID of the notification. I was hoping that a configuration in the model would be able to achieve this but I could not find anything in the guides, the docs or the source code of Rails.

I would like to keep the organization ID visible in the URL as this is an information that is used by our customers. So I do not want to use shallow nested resources for this problem.

We are using Rails 5.2.0.


Solution

  • You want the resolve route definition method.

    It is designed to do exactly what you want: configure a different behaviour when a single model instance is passed to url_for (as link_to does, for example).

    Specifically, in your config/routes.rb, something like:

    resolve("Notification") do |note|
      [:notification_organization, note.organization, note]
    end
    

    It sounds like you were on the right track -- it's just a routing concern rather than a model one.