Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Determine if an object has a named route

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?

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)
like image 732
Thilo Avatar asked Jun 19 '12 08:06

Thilo


People also ask

What are RESTful routes in Rails?

In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.

What is Mount in Rails?

Mounting rails are constructive items in electrical engineering and mechanical engineering projects; they are used to hold devices. A mounting rail is usually attached to a mounting panel or an enclosure profile.

What are resources in Rails routes?

Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.


2 Answers

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")
like image 98
Tigraine Avatar answered Oct 21 '22 07:10

Tigraine


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.

like image 3
Andrew Schwartz Avatar answered Oct 21 '22 06:10

Andrew Schwartz