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)
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.
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.
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.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With