DEV Community

Harun Sabljaković for Wizard Health

Posted on • Originally published at Medium

8 4

Dynamically direct routes for polymorphic associations - Ruby on Rails

Have you ever struggled with polymorphic associations? We all have, don’t worry.
Here’s an example of a polymorphic relationship.

class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
class Product < ApplicationRecord
has_many :pictures, as: :imageable
end

I’ve recently bumped into a problem where I had to list out all subjects (employees and products in this case) and when user interacted with one list item, it would redirect to that subject’s show page.

<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<% @imageable.each do |imageable| %>
<tr>
<td>
<%= link_to imageable.name, ?????? %>
</td>
</tr>
<% end %>
</tbody>
</table>
view raw index.html.erb hosted with ❤ by GitHub

You can see the problem, right? The obvious solution here would be to check the type of imageable and set the path helper accordingly. But, there’s a slightly more advanced technique for this use-case: direct method.
In your routes.rb file simply add this:

direct(:imageable) { |imageable| route_for ("#{imageable.class.name.underscore}".to_sym, imageable) }
view raw routes.rb hosted with ❤ by GitHub

And now you can use imageable_path(imageable) as a path helper that will dynamically resolve to imageable’s show page.
Now our example above becomes:

<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<% @imageable.each do |imageable| %>
<tr>
<td>
<%= link_to imageable.name, imageable_path(imageable) %>
</td>
</tr>
<% end %>
</tbody>
</table>
view raw index.html.erb hosted with ❤ by GitHub

Aaaand voilà, we’ve got a path helper that resolves to any imageable show page without the need to manually check for the type of imageable.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️