Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get route for base class of STI class in Rails

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?

like image 848
pjb3 Avatar asked Mar 31 '09 19:03

pjb3


1 Answers

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.

like image 147
Dave Ungerer Avatar answered Oct 06 '22 19:10

Dave Ungerer