Rails: Determine if an object has a named route
-
15-06-2021 - |
Question
In a Rails 3.1 app, I want to list a bunch of objects of variable class (from a polymorphic table) which I don't know in advance. For those that are resources with a named route, I'd like to use that route in a link_to
call. Naive approach without checking if such a route exists (excuse the HAML):
%ul
- @objects.each do |object|
%li= link_to object, url_for(object)
This will raise a undefined method 'foo_path'
error if the object is an instance of class Foo
which does not have a named route (for example because it's not defined as a resource). Is there an easy way (such as a simple method call) to determine the existence of a named route for an object or class?
EDIT:
What I would like to get is something like this:
%ul
- @objects.each do |object|
%li= link_to_if object.has_route?, object, url_for(object)
Solution
You could just add a rescue to your link_to call if you don't want model objects without named routes to be generated or output some error message for them
%ul
- @objects.each do |object|
%li= (link_to(object, url_for(object)) rescue "no link")
Hope this helps.
OTHER TIPS
Looking at the exact same problem. I don't like rescue for the same reason. I'm thinking
respond_to?(object.class.name.underscore + "_path")
This needs to be modified depending on nesting, subdomains, and STI; e.g., for my purpose I have:
respond_to?("ops_media_file_#{asset.class.base_class.name.underscore}_path")
and that seems to work pretty well.