Have you ever struggled with polymorphic associations? We all have, don’t worry.
Here’s an example of a polymorphic relationship.
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.
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:
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:
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.
Top comments (0)