Say I have a rails app with 3 models, Person, Place and Thing. Say the Thing uses single table inheritance, so there are FancyThing and ScaryThing subclasses. Then there are routes defined with map.resources :people, :places, :things
. So there are no controllers for FancyThings and ScaryThings, the ThingsController handles either type.
Now say I need to have code that shows a list of anything has links to them. If I have this code in my view:
<% @items.each do |item| %>
<%= link_to item.name, item %>
<% end %>
If item is a Person or a Place, this works fine, polymorphic_path
takes care of generating the correct route. But if item is a FancyThing or a ScaryThing, this blows up, because it will try to use fancy_thing_path
, which there is no route for. I want to somehow make it use thing_path
. Ideally there would be a method on Thing and/or its subclasses that somehow indicates the subclasses should use the base class to generate the route. Is there an elegant solution to this?
This will do the trick:
<% @items.map {|i| if i.class < Thing then i.becomes(Thing) else i end}.each do |item| %>
<%= link_to item.name, item %>
<% end %>
This uses the ActiveRecord function "becomes" to do an "up-cast" of all subclasses of Thing to the Thing base class.
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