Rails: determining if an object has a named route

In a Rails 3.1 application, I want to list a bunch of objects of a class of variables (from a polymorphic table) that I don’t know beforehand. For those who have resources with a named route, I would like to use this route in the link_to call. A naive approach without checking if such a route exists (sorry HAML):

 %ul - @objects.each do |object| %li= link_to object, url_for(object) 

This will undefined method 'foo_path' error if the object is an instance of the Foo class that does not have a named route (for example, because it is not defined as a resource). Is there a simple way (for example, a simple method call) to determine if a named route exists 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) 
+4
source share
2 answers

You can simply add a save to the link_to call if you do not want model objects without named routes to be generated or display some error message for them

 %ul - @objects.each do |object| %li= (link_to(object, url_for(object)) rescue "no link") 

Hope this helps.

+3
source

Looking at the same problem. I do not like salvation for the same reason. I think

 respond_to?(object.class.name.underscore + "_path") 

This needs to be changed depending on nesting, subdomains and STI; for example, for my purpose:

 respond_to?("ops_media_file_#{asset.class.base_class.name.underscore}_path") 

and it works very well.

+1
source

All Articles